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();
}
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With