KoffeeKoder


  • Random Expectations and Unit Testing
    published on 8/16/2008 10:43:41 PM
  • When we unit test we make sure that the result is correct by comparing it to our expectations. But what if the result of the method or module is random? How do we unit test that module?

    Recently, I had to unit test a method which returned random output (strings). And I had to test that the method indeed returns a random output (string).

    Here is the method:

    [Test]
            public void TestCanGetRandomMessage()
            {          
                string message = String.Empty;
                bool isRandom = false;

                for (int i = 0; i <= 5; i++)
                {
                    int randomNumber = rand.Next(messages.CreateUserWizardTitleBarMessage.Length);
                    Console.WriteLine(randomNumber);
                    if (!String.IsNullOrEmpty(message) && message != messages.CreateUserWizardTitleBarMessage[randomNumber].message)
                        isRandom = true;
                    else
                        message = messages.CreateUserWizardTitleBarMessage[randomNumber].message;   
                }

                Assert.AreEqual(true, isRandom);

            }


    Here I am simply calling the method again and again (5 times) and comparing it to the previous string. If it returns the same thing then the method is not working else everything is OK.

    The important thing about this method is the for loop which runs 5 times. Yes, the number 5 is important! If I put 1-2 then it will cause the test to fail since, we did not get enough tries to get the random result. It is even possible with 5 that we will get the same string again and again but then the probability of this is pretty low.