Re: Testing a class which utilizes randomness
Gishu Pillai <[email protected]> Fri, 4 Apr 2014 20:15:56 +0530
| Newsgroups | gmane.comp.programming.test-driven-development |
|---|---|
| Message-ID | <CABT02tsEkuFtx_ncPKH2NFvKv8Qe6ZRX5Xiptti6tZqY1t2DVA@mail.gmail.com> |
DR I think Nikola wants to test the real implementation of the random
string generator
off the top of my head
[Test]
public void GeneratesRandomStrings()
{
var list = new List<string>();
var generator = new RandomStringGenerator();
for(int i=0; i< [reasonableLength]; i++)
list.add(generator.Next());
// verify uniqueness of each item of the list
// e.g. create a Set with the elements and verify set.Count == list.Count;
}
On Fri, Apr 4, 2014 at 7:58 PM, David Rosenstrauch <[email protected]>wrote:
>
>
> On 04/04/2014 05:29 AM, Nikola Novak wrote:
> > Hello!
> >
> > I'm new to TDD and this group. For practice, I started a simple project
> and
> > now I want to create a list of random strings, but such that no two
> strings
> > are ever the same. In a very unlikely, yet possible case, when two
> randomly
> > generated strings are the same, the method that does this should discard
> > the duplicate and generate a new string before it returns.
> >
> > What I want to test is exactly this behavior - the code which discards
> the
> > duplicate and forces the string to be regenerated. To test that, I need
> to
> > force the random string generator to return a duplicate at least once
> (but
> > finite number of times). To create the test which would generate strings
> > until there's at least one duplicate is unrealistic, because such a test
> > could take a very long time to complete.
> >
> > How would I write such a test?
> >
> > Kind regards,
> > Nikola
>
> Trying abstracting away the notion of the random string generator, into
> an interface/parent class just called "string generator". Then make 2
> subclasses of that: your existing random string generator, and a "test
> string generator" that can return a predictable, deterministic sequence
> of values. For your unit tests, you would pass in an instance of the
> test string generator, while in the production code you would use the
> random string generator. Your code would work the same no matter which
> string generator it gets passed. But by using the test string generator
> in your unit tests you could control exactly the values being generated,
> and in that way make sure your program is handling all the edge cases
> correctly.
>
> HTH,
>
> DR
>
>
>