Welcome Guest! To enable all features please Login or Register.

Notification

Icon
Error

Bug with System.Random
Jonh04
#1 Posted : Monday, October 8, 2012 7:07:44 PM(UTC)
Rank: Member

Groups: Registered
Joined: 3/13/2012(UTC)
Posts: 20

Thanks: 1 times
Was thanked: 3 time(s) in 2 post(s)
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);

}
}
Remco
#2 Posted : Monday, October 8, 2012 8:39:51 PM(UTC)
Rank: NCrunch Developer

Groups: Administrators
Joined: 4/16/2011(UTC)
Posts: 7,145

Thanks: 961 times
Was thanked: 1291 time(s) in 1197 post(s)
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
Users browsing this topic
Guest
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

YAF | YAF © 2003-2011, Yet Another Forum.NET
This page was generated in 0.024 seconds.
Trial NCrunch
Take NCrunch for a spin
Do your fingers a favour and supercharge your testing workflow
Free Download