Re: Testing a class which utilizes randomness
Steven Gordon <[email protected]> Fri, 4 Apr 2014 09:09:40 -0700
| Newsgroups | gmane.comp.programming.test-driven-development |
|---|---|
| Message-ID | <CAF7qo6Uv=Y43axm-e+TwKe4+Gzr3sx=y32Z81prEwbOTGOPGRg@mail.gmail.com> |
On Fri, Apr 4, 2014 at 2:29 AM, Nikola Novak <[email protected]> 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. > Ever? Is that even possible? > 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? > > There must be some part of the code that "remembers" what it has previously generated and checks whether the string just generated is among them. So, shouldn't this part of the code be put into a separate function with its own unit tests. This function must have the candidate string as a parameter and the history as the class or parameter, so you can TDD this logic with whatever inputs your unit tests needs, right? That tests whether the function does what it is supposed to. You would also have to TDD that the history structure is being correctly built. If you then want to also test whether all the code works together, if you can inject the length of the strings and the character set they are generated from, then you can be sure that for a very small length and character set, duplicates will get generated quickly enough to validate that it really works. More interesting is how you could test whether the strings generated are sufficiently "random". > Kind regards, > Nikola > > >