Moq验证使用指定顺序的不同参数调用相同的方法

时间:2013-02-07 12:57:19

标签: c# unit-testing moq

这是我需要进行单元测试的方法:

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

如何配置模拟TextWriter以验证某些参数是否按特定顺序传递给同一方法(WriteLine)?

[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();
}

1 个答案:

答案 0 :(得分:4)

您可以使用Callback验证每个调用的传递参数:

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