moq Validating call order implicitly


Where a method to be tested uses information from one call to pass on to subsequent calls, one approach that can be used to ensure the methods are called in the expected order is to setup the expectations to reflect this flow of data.

Given the method to test:

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

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


Expectations can be set to pass data from GetInitialValue through PrefixString and ReverseString to DoStuff, where the information is verified. If any of the methods are called out of order, the end data will be wrong and the test will fail.

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

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