在测试夹具设置中运行时生成相同的随机数
我试图在使用 NUnit 测试期间生成一个随机数,但它一直生成相同的数字。 我为此目的使用以下函数。
dim dCount As Integer = Math.Floor((High - Low + 1) * Rnd() + Low)
dim divName As String = "abc" & dCount
知道为什么要这样做吗?
问候,
萨姆
I am trying to generate a random number during testing using NUnit, but it keeps generating the same number. I am using the following function for this purpose.
dim dCount As Integer = Math.Floor((High - Low + 1) * Rnd() + Low)
dim divName As String = "abc" & dCount
Any idea why it is doing this?
Regards,
Sam
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
想必您正在快速连续执行许多测试。 我不知道
Rnd()
在 VB 中具体做什么,但听起来它有典型的“每次调用新的 RNG”问题。创建
Random
的单个实例并重复使用它。 请注意,您的数学可以用一个简单的方法代替:一个警告 -
Random
不是线程安全的。 如果您需要从不同线程生成随机数,要么使用锁定或线程静态。另一点:使用随机数将使您的单元测试具有不确定性。 你确定你必须这样做吗? 有时它是合适的,但通常不是 IME。
Presumably you're executing many tests in quick succession. I don't know exactly what
Rnd()
does in VB, but it sounds like it's got the typical "new RNG per call" problem.Create a single instance of
Random
and use it repeatedly. Note that your maths can be replaced by a simple:One caveat -
Random
isn't thread-safe. If you need to generate random numbers from different threads, either use locking or thread statics.On another point: using random numbers will make your unit tests non-deterministic. Are you sure you have to? Sometimes it's appropriate, but not often IME.