在测试夹具设置中运行时生成相同的随机数

发布于 2024-07-14 09:08:01 字数 242 浏览 7 评论 0原文

我试图在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苦笑流年记忆 2024-07-21 09:08:01

想必您正在快速连续执行许多测试。 我不知道 Rnd() 在 VB 中具体做什么,但听起来它有典型的“每次调用新的 RNG”问题。

创建 Random 的单个实例并重复使用它。 请注意,您的数学可以用一个简单的方法代替:

dim dCount as Integer = myRandom.Next(Low, High+1)

一个警告 - 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:

dim dCount as Integer = myRandom.Next(Low, High+1)

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.

林空鹿饮溪 2024-07-21 09:08:01
Dim dCount As Integer = between(low, high)
Dim divName As String = "abc" & dCount


Dim myRandom As New Random
Private Function between(ByVal low As Integer, ByVal high As Integer) As Integer
    between = myRandom.Next(low, high + 1)
End Function
Dim dCount As Integer = between(low, high)
Dim divName As String = "abc" & dCount


Dim myRandom As New Random
Private Function between(ByVal low As Integer, ByVal high As Integer) As Integer
    between = myRandom.Next(low, high + 1)
End Function
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文