In the last blog post I talked about how to use Moq’s built in SetupSequence to create a “chain” of actions to execute for subsequent calls of the same mocked method.
This works great for the simple case, but falls down when you have to do something a little more complicated like, say, issue a callback.
When you’re creating single setups on a mocked object, there’s a lot of flexibility for figuring out what to return.
Return the object directly:
Run a Func that returns the object:
Issue a callback when the method is called:
However, not with SetupSequence.
SetupSequence does not offer the same flexibility.
You can’t provide a function to Returns, nor can you issue a callback. The only option you have is to return the object directly.
In my case, I wanted to use the Func
One Solution
I came up with this class and extension method to bolt on the functionality I wanted into Moq. Moq is open source, so I’m sure if I was more ambitious I could create a full suite of functionality (that isn’t as clunky) and submit a PR, but this gets it done for me in the present:
Usage
To use, just do a .Sequence after doing a .Setup: