Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here's a method I need to unit test:

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

How can I configure a mock of TextWriter to verify that certain arguments are passed to the same method (WriteLine) in a certain 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();
}
like image 650
Cristian Diaconescu Avatar asked Feb 07 '13 12:02

Cristian Diaconescu


1 Answers

You can use Callback to verify 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));
}
like image 72
Sergey Berezovskiy Avatar answered Oct 12 '22 16:10

Sergey Berezovskiy