Say that you’re unit testing and you want a mocked interface to behave differently for different calls to the same method.
I was trying to test a TCP listener loop – a TcpListener waits for an incoming connection, does something with it, and then goes back to listening. In essence, the loop will last until the program is closed or the listener is canceled… but that’s not great for unit testing. I wanted to test to make sure that, given an error condition the first time, the TcpListener loop would loop back around and try again.
Moq’s SetupSequence
Moq has a built-in way of doing this – SetupSequence. When defining the behavior of your mock, you just chain together the desired result. The next link in the chain will be returned for each subsequent call of the method. This works with synchronous or asynchronous methods, and you can even throw exceptions as part of the chain.
Note that I’m also using the FluentAssertions library. Its a neat little library that gives you some fluid syntax when doing assertions, and, if you’re a Linq junky like me, it just feels right.
Moq sequential callbacks – Darchuk.NET
[…] the last blog post I talked about how to use Moq’s built in SetupSequence to create a “chain” of actions to […]