Skip navigation.

Successive Method Calls with Stubs

Successive Method Calls with Stubs

Phil Haack recently wrote a blog post about a tricky use of Moq where one needs to set expectations for successive method calls. Here’s the specification of the problem shamelessly copied from his blog post:

image

So we want to set up a mock to return 0 or more ‘true’ and a final false. With Moq and the help of an extension method, Phil managed to express this in a single line of C#.

image 

Let’s do it with Stubs!

Stubs is a stub framework solely based on delegates. In that sense, it does not provide any helper to express a sequence of calls so we need to do that in C#. An easy approach is to create an array and use a counter to iterate through it (sounds familiar right?). This is exactly that this snippet does:

image

SIDataReader is the code generated stub type of IDataReader. It has a field Read of type Func<bool> that can used to stub the Read() method.

Putting Pex into the mix

Why did we have to specify the values in the test? We should let Pex decide the sequence of booleans that are relevant to test code. To do so, we refactor values as a parameter and add an assumption to ensure that the last element is false.

image

Voila!