Moq 是测试双打

模拟是指测试双打,允许验证与模拟的交互,它们并不意味着取代你正在测试的系统。示例通常会演示 Moq 的功能如下:

// Create the mock
var mock = new Mock<IMockTarget>();

// Configure the mock to do something
mock.SetupGet(x => x.PropertyToMock).Returns("FixedValue");

// Demonstrate that the configuration works
Assert.AreEqual("FixedValue", mock.Object.PropertyToMock);

// Verify that the mock was invoked
mock.VerifyGet(x => x.PropertyToMock);

虽然这个例子显示了使用 mock 所涉及的步骤,但重要的是要记住它实际上并没有测试任何东西,除了模拟已经正确设置和使用。使用模拟的实际测试将模拟提供给要测试的系统。要测试以下方法:

public class ClassToTest
{
    public string GetPrefixedValue(IMockTarget provider)
    {
        return "Prefixed:" + provider.PropertyToMock;
    }
}

可以创建依赖接口的模拟:

public interface IMockTarget
{
    string PropertyToMock { get; }
}

要创建实际验证 GetPrefixedValue 方法行为的测试:

// Create and configure the mock to return a known value for the property
var mock = new Mock<IMockTarget>();
mock.SetupGet(x => x.PropertyToMock).Returns("FixedValue");

// Create an instance of the class to test
var sut = new ClassToTest();

// Invoke the method to test, supplying the mocked instance
var actualValue = sut.GetPrefixedValue(mock.Object);

// Validate that the calculated value is correct
Assert.AreEqual("Prefixed:FixedValue", actualValue);

// Depending on what your method does, the mock can then be interrogated to
// validate that the property getter was called.  In this instance, it's
// unnecessary since we're validating it via the calculated value.
mock.VerifyGet(x => x.PropertyToMock);