Re: Testing a class which utilizes randomness

Ron Jeffries <[email protected]> Fri, 4 Apr 2014 14:48:01 -0400
Newsgroups gmane.comp.programming.test-driven-development
Message-ID <[email protected]>
Mark,

On Apr 4, 2014, at 2:39 PM, Mark Levison <[email protected]> wrote:

> All you've done is test with you've approximately built a random number generator. My underlying point was the OP might want to choose a slightly saner problem.


I think not. OP said:

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

To test duplicate removal, one need not test the RNG at all. It’s the STRINGS that have to not be duplicated. It will take many rolls of the RNG to get one string. So at first it seems that what one must do is generate the random string and then test whether it is duplicated.

But no. The code partitions into getting a string and seeing whether it is duplicated and putting it away if it is not. The source of the string is irrelevant to the other two. You can test those two, however they are partitioned, by storing Pig, Dog, Chicken, Dog and making sure you only get Pig Dog and Chicken. 

In fact, I’d just check that I had three, if the code shaped up like I expect it would. Or even just test isThisAlreadyThere, depending on how it flows. 

In no case is it necessary to look at the RNG. The issue isn’t in not creating a duplicate, it’s in not storing it. Offhand, I can’t think of a good way to prevent creating a duplicate, since AAAAAB != AAAAAC.

Ron Jeffries
www.XProgramming.com
I'm not bad, I'm just drawn that way.  -- Jessica Rabbit