Re: Testing a class which utilizes randomness

Ron Jeffries <[email protected]> Fri, 4 Apr 2014 12:49:39 -0400
Newsgroups gmane.comp.programming.test-driven-development
Message-ID <[email protected]>
Hi Nikola,

On Apr 4, 2014, at 5:29 AM, Nikola Novak <[email protected]> wrote:

> 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?


One could:

Have a method boolean containsString(aString) and test that.
Have a method putIfAbsent(aString) and test that (by putting the same string twice and observing that I still only have one string.

Or something approximately like that.

I generally try to avoid something like boolean putString(aString) that returns whether it accepted the string or not, because I try to avoid methods that return a value and do something. I might put up with it but probably not.

There are more ways ...

Ron Jeffries
www.XProgramming.com
I have two cats, and a big house full of cat stuff. 
The cats fight and divide up the house, messing up their own lives. 
Nice work cats. 
Meow.