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()
?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Set it with instance of Random with your seed or just extend the methods to return values you need
How about creating an instance of
Random
yourself and using that instead?Math.random()
creates one and uses that, so I don't think that you can mess with its seed. If you create aRandom
and use it directly, however, you can set the seed for that when you create it, and/or you can callsetSeed()
on it later.The method
Math.random()
uses a private static field: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.