-1

I'm looking to unit test a method that returns a random float as an ID. I am trying to use Red Green Refactor, but am stumped by the randomness of the code. Below find the method I am trying to test. I am aware that I am technically supposed to write the test first, but I don't know how to test for random.

public Random ReturnDevID()
                {
                    var rnd = new Random();
                    rnd.NextDouble();
                    return rnd;
                }
Peter O.
  • 32,158
  • 14
  • 82
  • 96
  • 1
    Note that code in the post is absolutely wrong example of using `Random` - https://stackoverflow.com/questions/767999/random-number-generator-only-generating-one-random-number – Alexei Levenkov Nov 20 '19 at 18:30

1 Answers1

0

It's a bit of weird test to write. I personally don't think you need it, but if you want to you could try something like this (I also changed your implementation because it returns an instance of Random, not a random float):

public double ReturnDevID()
{
     var rnd = new Random();
     return rnd.NextDouble();
}

public void TestRandom()
{
     // Call the method 100 times and save the result in a list
     var randoms = Enumerable.Range(0, 100)
                             .Select(i => ReturnDevID())
                             .ToList();

      // Make sure you have no duplicates
      Assert.AreEqual(randoms.Count, randoms.Distinct().Count());
}
Kenneth
  • 28,294
  • 6
  • 61
  • 84
  • You may want to check linked duplicate too - random is not just distinct - i.e. "In addition to testing that the function returns a date in the desired range, you want to ensure that the result is well-distributed." I.e. the test you've suggested happily accepts `public double ReturnDevID => lastValue ++;` as "random". – Alexei Levenkov Nov 20 '19 at 18:27
  • 1
    Side note: the code sample shows wrong usage of `Random`... – Alexei Levenkov Nov 20 '19 at 18:34
  • @AlexeiLevenkov Yes, you are correct, the sample shows the wrong usage of Random, which I indicated in the answer. On the other hand, the question was not "is my random implementation correct?", the question was "how do I test it?". I don't agree with the assesment that it's a duplicate. The linked post just shows correct usage of random, not how to test it – Kenneth Nov 20 '19 at 22:59
  • With regards to how to test it, this is an approximation. I personally don't see the value in testing it, but would you mind elaborating on a proper way to test it? – Kenneth Nov 20 '19 at 23:00