'Is there a way to mock Random.Next regardless of what gets passed to it and where it gets called?
I have the following method I wish to unit test:
public class Board
{
public static BoardElement RandomElement(List<BoardElement> elements)
{
int index = Random.Next(elements.Count);
return elements[index];
}
}
This method calls Random.Next(elements.Count)
.
I tried to create a mock of Random
so that Random.Next(int maxValue)
returns a controlled integer regardless of the int maxValue
passed:
Random.Setup(random => random.Next(It.IsAny<int>())).Returns(randomInt);
The whole test function is as follows:
[Theory]
[MemberData(nameof(TestData.RandomElement_TestData), MemberType = typeof(TestData))]
private static void Test_RandomElement(List<BoardElement> elements, int randomInt)
{
Mock<Random> Random = new Mock<Random>();
Random.Setup(random => random.Next(It.IsAny<int>())).Returns(randomInt);
BoardElement element = Board.RandomElement(elements);
Assert.Equal(elements[randomInt], element);
}
Is there a way to setup Random.Next
to return a controlled integer regardless of where it is called?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|