Re: Testing a class which utilizes randomness
David Rosenstrauch <[email protected]> Fri, 04 Apr 2014 10:28:03 -0400
| Newsgroups | gmane.comp.programming.test-driven-development |
|---|---|
| Message-ID | <[email protected]> |
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