Testing Random code


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?



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.


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: ,

Posted 08-04-2009 5:16 PM by Krzysztof Koźmic
Filed under:



Daniel Hölbling wrote re: Testing Random code
on 08-04-2009 7:00 PM

Wouldn't it just be simpler to hide the whole thing behind a interface?


interface IRandom {

double NextDouble();


Writing an adapter for the real Random thing becomes very simple and you can do even more crazy stuff.

Anyway, thanks for pointing out that Random has virtual members. May come in handy one day.

But the usual use case is either it's behind a interface or it's just newed up in code (when working with legacy code)

public void Foo()


var rnd = new Random();



Krzysztof Koźmic wrote re: Testing Random code
on 08-05-2009 1:39 AM

You could if you needed richer interface, which in most cases you don't and why duplicate what's already in the framework.

Tuna Toksoz wrote re: Testing Random code
on 08-05-2009 6:52 AM

new'ing random everytime might lead to a problem, they may give the same result in case you are new ing and using them one after the other, such as

Assert.Eq(new Random().Next(),new Random().Next())

is likely to pass

Mark wrote re: Testing Random code
on 08-05-2009 3:52 PM

Krzysztof, nice observation. This will come in handy for some games I plan on making at some point in the future. Thanks!



Sanjeev Agarwal wrote Daily tech links for .net and related technologies - August 7-10, 2009
on 08-09-2009 3:36 AM

Daily tech links for .net and related technologies - August 7-10, 2009 Web Development Best Free Website

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET


SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
NHibernate Profiler
Balsamiq Mockups
JetBrains - ReSharper
Web Sequence Diagrams
Ducksboard<-- NEW Friend!


Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers


Community Server (Commercial Edition)