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);