Set seed on Math.random()

Kevin picture Kevin · May 14, 2010 · Viewed 14.8k times · Source

I need to write some junit tests on Java code that calls Math.random(). I know that I can set the seed if I was instantiating my own Random object to produce repeatable results. Is there a way to do this also for Math.random() ?

Answer

rsp picture rsp · May 14, 2010

The method Math.random() uses a private static field:

private static Random randomNumberGenerator;

If you really really need to set this to a new Random(CONSTANT_SEED) (for instance you need to JUNit test code which you have no control over) you could do so by using reflection.