Moq verifies that the same method is called with different arguments in the order specified

Here I need a unit test:

void Do(IEnumerable<string> items, TextWriter tw){
    foreach(var item in items) { tw.WriteLine(item); }
} 

      

How do I set up a mock TextWriter

to check that certain arguments are passed to the same method ( WriteLine

) in a specific order?

[Test]
public void Test(){
    var mock = new Mock<TextWriter>();
    mock.Setup( ??? ); //check that WriteLine is called 3 times, 
                       //with arguments "aa","bb","cc", in that order.

    Do(new[]{"aa", "bb", "cc"}, mock);
    mock.Verify();
}

      

+3


source to share


1 answer


You can use Callback to check the passed parameter for each call:



[Test]
public void Test(){
    var arguments = new[]{"aa", "bb", "cc"};
    var mock = new Mock<TextWriter>();
    int index = 0;
    mock.Setup(tw => tw.WriteLine(It.IsAny<string>()))
        .Callback((string s) => Assert.That(s, Is.EqualTo(arguments[index++])));

    Do(arguments, mock.Object);
    mock.Verify();
    // check all arguments where passed
    Assert.That(index, Is.EqualTo(arguments.Length));
}

      

+3


source







All Articles