隱式驗證呼叫順序

如果要測試的方法使用來自一個呼叫的資訊傳遞給後續呼叫,則可以用於確保以預期順序呼叫方法的一種方法是設定反映此資料流的期望。

鑑於測試方法:

public void MethodToTest()
{
    var str = _utility.GetInitialValue();

    str = _utility.PrefixString(str);
    str = _utility.ReverseString(str);

    _target.DoStuff(str);
}

期望可以設定為將資料從 GetInitialValue 傳遞到 PrefixStringReverseStringDoStuff,在那裡驗證資訊。如果任何方法無序呼叫,則結束資料將出錯並且測試將失敗。

// Create mocks
var utilityMock = new Mock<IUtility>();
var targetMock = new Mock<ITarget>();

// Setup expectations, note that the returns value from one call matches the expected
// parameter for the next call in the sequence of calls we're interested in.
utilityMock.Setup(x => x.GetInitialValue()).Returns("string");
utilityMock.Setup(x => x.PrefixString("string")).Returns("Prefix:string");
utilityMock.Setup(x => x.ReverseString("Prefix:string")).Returns("gnirts:xiferP");

string expectedFinalInput = "gnirts:xiferP";

// Invoke the method to test
var sut = new SystemUnderTest(utilityMock.Object, targetMock.Object);
sut.MethodToTest();

// Validate that the final call was passed the expected value.
targetMock.Verify(x => x.DoStuff(expectedFinalInput));