Build/Test Issues

Bug with System.Random

Started by Jonh04 on 5,246 views

Hello!

Just stumbled unto a bug I think.

the following code fails in ncrunch

public class Class1
{
public int Random { get; set; }

public Class1()
{
Generate();
}

public void Generate()
{
var generator = new Random();

Random = generator.Next(1, 1000);
}
}

[TestClass]
public class MyTestClass
{
[TestMethod]
public void MyTestMethod()
{
var instance = new Class1();
var random = instance.Random;

instance.Generate();

Assert.AreNotEqual(random, instance.Random);

}
}
Hi John, thanks for sharing this issue.

The problem appears to be caused by the code itself. I was able to surface the issue in a multitude of different test runners and confirmed that it happens intermittently.

The constructor for the Random class, by default, will initialise itself using the current system timer. The system timer is updated only intermittently during code execution (i.e. it is normal for multiple lines of code to be executed with the same number of ticks on the timer). As such, the Random class is being created twice in rapid succession with the same seed. This results in the same value being returned from the 'Next' method between different instances of the same class.

I suggest changing the test so that the constructor call for the Random class is moved into the constructor of Class1, with the result stored as a private member. In this way, you don't need to recreate the Random instance before each retrieval of a new random number. This will prevent the Random instance from being reinitialised with the same seed and thus returning the same result.

I hope this helps!


Cheers,

Remco

Post a reply

Log in to reply.