Framework Tips XIII: Testing Random code

Question

How do you test code that is random. For example say you have a class that allows some action with 60% probability:

public class UsingRandom
{
    private Random generator;
    public double probability = 0.6D;
 
    public bool ShouldAllow()
    {
        return generator.NextDouble() < probability;
    }
}

How do you unit test that?

 

Answer

The answer is staggeringly simple – you fake it. Raise your hand if you knew that methods in the Random class are virtual (I didn’t). Ok, now you can put your hand down, both of you.

virtual_random

With that knowledge, all you have to do is to inject an appropriate fake into the class during your test, and you’re done.

 

Technorati Tags: ,