在Math.random()上设置种子 [英] Set seed on Math.random()
本文介绍了在Math.random()上设置种子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在调用Math.random()
的Java代码上编写一些junit测试.我知道如果实例化我自己的Random对象以产生可重复的结果,则可以设置种子.有没有办法对Math.random()
执行此操作?
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()
?
推荐答案
方法Math.random()
使用私有静态字段:
The method Math.random()
uses a private static field:
private static Random randomNumberGenerator;
如果您确实确实需要将其设置为new Random(CONSTANT_SEED)
(例如,您需要JUNit无法控制的测试代码),则可以使用 reflection .
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.
这篇关于在Math.random()上设置种子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文