-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;
                }
1

1 Answer 1

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());
}
Sign up to request clarification or add additional context in comments.

4 Comments

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".
Side note: the code sample shows wrong usage of Random...
@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
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.