I have a public static method that uses an object of Random class to generate an integer. The integer is then made the index of a List. I want to test the logic of the method while having control over what a random object's Next method returns.
public class RandomGenerator
{
// a static method which produces a random selection from a List
public static string GetRandomListMember(List<string> anyStringList)
{
Random rand = new Random();
int randomInt = rand.Next(anyStringList.Count);
return anyStringList[randomInt];
}
}
From my MSTest file:
[TestClass]
public class RandomGeneratorSpec
{
[TestMethod]
public void GetRandomListMember_ListOfStrings()
{
List<string> strings = new List<string> { "red", "yellow", "green" };
Mock<Random> mockRandom = new Mock<Random>();
mockRandom.Setup(rand => rand.Next(strings.Count)).Returns(() => 2); // 2!
string result = RandomGenerator.GetRandomListMember(strings);
Assert.AreEqual("green", result);
}
}
I want mockRandom.Next to return 2 every time it runs in this test. Obviously, this isn't the way to do it. I've been searching through examples, but they all seem to utilize methods on the object and with instance methods instead of static methods.
How do I control what a built-in method returns while unit testing a method that utilizes it?
Aucun commentaire:
Enregistrer un commentaire