5

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

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

1 回答 1

6

您可以使用 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));
}
于 2013-02-07T13:02:33.553 回答