Do you know Random will generator same result?
2014/11/12 min read
bookmark this
I wrote a IEnumberable extension like following, and with unit test.
return source.Select(x => new { Index = RandomGenerator.Next, Value = x })
Do you know that the result will return the same number if I run the extension I created 100 times.
[TestMethod] public void Linq_AfterShuffle100TimesResultShouldBeContainsAllValues() { List target = new List { 1,2,3,4,5,6,7,8,9,10 }; List resultCheck = new List(); for (int i = 0; i < 100; i++) { resultCheck.Add(target.Shuffle(1).ToList().FirstOrDefault()); } resultCheck = resultCheck.Distinct().OrderBy(x => x).ToList(); Assert.IsTrue(target.Count() == resultCheck.Count()); for (int i = 0; i < target.Count - 1; i++) { Assert.AreEqual(target[i], resultCheck[i]); } Assert.AreEqual(10, resultCheck.Count()); }
I totally didn't notice this, until I checked the MSDN, random. MSDN Random
So I have to create a single instance random object.
public static class RandomGenerator { private static Random _random; private static object _instance = new object(); static RandomGenerator() { _random = new Random(); } private static Random GetObject { get { lock (_instance) { if (_random == null) { _random = new Random(); } return _random; } } } public static int Next { get { return _random.Next(); } } }
My point is, Unit Test is so important, if you wirte code as TDD. You'll notice problem like this and you're become a better developer.