我正在尝试使用Moq中的It类提供正数:
It.Is<int>(a => a > 0)
但是结果始终等于0。实现此目标的正确方法是什么?
听起来您的测试有点低级,应该测试代码的逻辑,该代码根据接收到的值而不是值本身执行操作。话虽如此,这里有些代码可能会有所帮助。它包装了内置的.NET随机数生成器,以确保输出已知的数字序列。
[TestMethod]
public void VerifyMultipleValues()
{
// Define values to return
var values = new[] {5, 9, 10};
// Create a mock of the interface
var mockRand = new Mock<IRandomNumber>();
// Define behaviour of the mock
mockRand.Setup(m => m.GetRand(It.IsAny<int>())).ReturnsInOrder(values);
// Point the factory output at the mock object
DomainFactory.RandomNumber = mockRand.Object;
// Create an instance of the wrapper object
// The wrapper calls the factory which in turn calls the mock object that was just created
// to return known values
var wrapper = new Wrapper();
foreach (var v in values)
{
var output = wrapper.GetNumber(100);
Assert.AreEqual(v, output);
}
// Clean up
DomainFactory.RandomNumber = null;
}
ReturnsInOrder是源自here的扩展方法。
public static void ReturnsInOrder<T, TResult>(this ISetup<T, TResult> setup,
params TResult[] results) where T : class
{
setup.Returns(new Queue<TResult>(results).Dequeue);
}
其余代码如下:
// Interface
public interface IRandomNumber
{
int GetRand(int end);
}
// Implementation
public class RandomNumber : IRandomNumber
{
private static readonly Random _random = new Random();
public int GetRand(int end)
{
return _random.Next(0, end);
}
}
// Factory
public static class DomainFactory
{
private static IRandomNumber _randomNumber;
public static IRandomNumber RandomNumber
{
get { return _randomNumber ?? (_randomNumber = new RandomNumber()); }
set { _randomNumber = value; }
}
}
// Wrapper
public class Wrapper
{
public int GetNumber(int parameter)
{
return DomainFactory.RandomNumber.GetRand(parameter);
}
}