tags:

views:

87

answers:

2

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

+1  A: 

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.

Jon Skeet
Rnd() returns a single in the range 0 <= r < 1... and I'll have to second not using randomly-generated data in your unit tests. Much better to explicitly test inside and outside your expected range.
Jim H.
Personally, I recommend random numbers with a fixed seed (+ explicit limit cases of course). That way, you can easily test a large array of data, and encounter subtle problems you might have missed, yet always repeat the exact same test for regression purposes.
Kena
A: 
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
dbasnett