I love Moq which is a little micro framework for controlling the behavior of dependencies, or at least that is how usually use it…sort of. (some might call it a mocking framework…well, anyway)

One of the disadvantages of Moq however is that the syntax can be a bit complicated and the arrange part of the arrange-act-assert pattern sometimes becomes a bit unreadable, taking the focus away from the actual arrange.
This is especially true when it comes to expectation setup chaining which I’ll show you in the following little example.

Expectation setup chaining

Well, there’s a little three word sentence that I just came up with. Let me show you what I mean with that.

Background

For the purpose of this post I’m going to use an example from another framework called N2CMS. You don’t need to know much about N2CMS other than it uses the concept of a content item which can have children.

I’m writing a component, ContentItemReverser, which can take a hierarchy of content items and reverse them.

Since content item is an abstract class and I’m only interested in the actual component I’m using Moq to setup the hierarchy below:

When reversing them I expect the order to be 12, 11, 10

Let’s go…

“Traditional” Moq Style

Here’s a look at how a test for the ContentItemReverser’s Items property would look like:

One things that has always bothered me with Moq is that the code for doing Setups/Expectations/Arrange (or what have you) is pretty tedious and you end up with extension methods or some other mechanism for controlling them. Especially if you are doing multiple setups the test quickly becomes hard to read…which you can see from the code already.

Summary: there’s a lot of setup code which in turn takes the focus away from the actual test.

“Functional” Moq Style

Here’s a version of that exact same test using the new functional style setup available in Moq 4:

There’s still a lot of setup code but at least in holds together and you can see the “hierarchy”…right!?

The approach above uses the new functional setup style setup available in Moq 4.
Since all we want here is to “chain” (or use the next step in the chain as input to the prior) the setup calls, Moq 4 helps us make the arrange more readable.

This is of course a matter of taste and you can also use a mix of the two approaches which I’ll show in future posts perhaps.