Mock Randomizer

MockRandomizer means using a random number generator which you have modified or overridden to make its output predictable. It might always return the same value, or a predictable sequence.

A mock randomizer helps when UnitTestingNonDeterministicCode by making it deterministic. (Caveat: Must be "randomizer-driven", i.e. the non-nondeterminism isn't a consequence of a physical process, OS scheduling, etc). It allows: if (if get this random result) then assert(this state should hold). Accordingly, the test should predictably pass or fail.

An alternative stochastic approach is to repeat a test many times, and verify that the statistically expected result occurs on average within a stated tolerance. Naturally, sometimes such a test will fail or pass when it shouldn't have. The advantages of MockRandomizers over stochastic approaches are that they're less work to setup, and don't ever false positives or negatives.

A simple Java MockRandomizer example:

 Deck = new Deck();
 deck.setRandom(new Random() {
public void nextDouble() {
return 0.0;
}
 });
 deck.shuffle();

We can mechanically work out what state a shuffled deck should be in, when all random call are zero, and assert it in the usual fashion. In my experience this does usefully exercise the code I want to test, though you may need several different MockRandomizers? to cover your cases.


EditText of this page (last edited September 1, 2004) or FindPage with title or text search