Fluent Mocking
June 22, 2011 1 Comment
In which our hero shouts “Hold on thar pilgrims” at those who would hate Mocking Frameworks.
Here’s a scenario (for once not a hypothetical scenario, this is a real system I worked on). You’re building a wizard based app. To be more accurate you’re building lots of wizard based apps, so you’ve extracted all the wizardy stuff up into it’s own classes. Your apps can now focus on actual bread and butter functionality. When I say ‘You’ I mean ‘I’ but this is a writing device that sucks you into the narrative. I bet deep down you already care a little bit about how these Wizards turned out.
Two of the objects in your Wizardy Stuff code are a ‘Wizard’ and a ‘WizardStep’. A Wizard obviously contains a number of WizardSteps. You get the idea.
There are quite a few tests that we can write to make sure that navigation works. A Wizard has a current step, Moving Next or Previous should increment or decrement the current step. Moving next on the last step causes the Wizard to finish. It’s all very simple, and what you’d expect from a wizard.
Let’s look at an example of the kind of tests we might have to write, and what it means in terms of mocks and stubs. We have a requirement that says that when the user clicks ‘Move Next’ the current step gets to validate itself and decide whether it will allow the Move Next to happen. If it returns false, the Wizard will refuse to allow the user to move on.
To test a feature like this we can do the following:
- Create a wizard with one step
- Use a stub for step1 that returns false when the OKToMoveNext method is called
- Start the wizard
- Assert that we’re on the first step
- Attempt to move next
- Assert that we’re still on the first step
After the attempt to MoveNext we should still be on step1 (because step1 returns false when asked to validate itself).
We can implement the test in various ways. A key issue is how to implement the stub for step1 that simulates a step failing validation. Here’s one example, using the Moq Framework:
// Listing 1
[Test()]
public void Validation_CanPrevent_MoveNext()
{
Mock<IWizardStep> step1 = new Mock<IWizardStep>();
step1.Setup(s => s.OKToMoveNext()).Returns(false);
Wizard wizard = new Wizard()
.AddStep(step1.Object)
.Start();
Assert.AreEqual(step1.Object, wizard.CurrentStep);
wizard.MoveNext();
Assert.AreEqual(step1.Object, wizard.CurrentStep);
}
I don’t like this code. It’s too busy. There’s too much “stuff” that’s related to the mocking framework. The intent of the test might be discernible, but only just. The shaded lines in particular need a second or third glance to make sure you’re reading them right. Our intent is to create a stub wizard step that can’t move next. Our test should be screaming that intent so clearly that it cant be missed by someone reading the code.
I suspect that scenarios like this are one of the reasons why some developers find themselves edging back towards hand-rolled mocks and stubs. The equivalent code using hand-coded classes is much simpler and the intent of the test is clearer:
// Listing 2
[Test()]
public void HM_Validation_CanPrevent_MoveNext()
{
IWizardStep step1 = new WizardStepThatIsNotOKToMoveNext();
Wizard wizard = new Wizard()
.AddStep(step1)
.Start();
Assert.That(wizard.CurrentStep == step1);
wizard.MoveNext();
Assert.That(wizard.CurrentStep == step1);
}
The shaded code tells most of the story. Because we’re creating a simple class for a specific purpose, we can be very explicit with our naming.
Although listing 2 is an improvement over the code we produced using the Moq mocking framework, it’s not without it’s troubles. Our suite of tests is going to need a lot of different mocked WizardSteps to cover the various scenarios. Many will be very similar, or will have parts that are identical to parts of others. For example, we might have half a dozen version of the class that need to prevent a user Moving Next, but each may need to do that in conjuction with some other different behaviour.
We could try to make our Handmade mocks more intelligent, but that’s a slippery slope. Once you start adding in “one more little tweak, to facilitate one more test”, you quickly find yourself with a mock that’s more complex than the code you’re trying to test.
One interesting option is to go back to using our Mocking Framework, but hide the messiness of it behind a slightly nicer abstraction. Imagine being able to write a test like the one in Listing 3:
// Listing 3
[Test()]
public void step_can_stop_move_next()
{
IWizardStep step1 = new MockWizardStep()
.ThatCannot.MoveNext
.Object();
Wizard wizard = new Wizard()
.AddStep(step1)
.Start();
Assert.AreEqual(step1, wizard.CurrentStep);
wizard.MoveNext();
Assert.AreEqual(step1, wizard.CurrentStep);
}
This is a fluent style interface, but behind the scenes it’s doing all the same stuff that our first test did. The beauty of a mocking framework is that you can assemble the functionality you desire at runtime, rather than needing to code a specific class for the specific case you want to test. Once you’ve written the Factory that spits out mocks, you can use it to spit out other variations of the MockWizardStep:
// Listing 4
IWizardStep step1 = new MockWizardStep()
.ThatCan.MoveNext
.Object();
IWizardStep step1 = new MockWizardStep()
.ThatCan.MoveNext
.ThatCannot.MovePrevious
.Object();
Once you have the fluent interface in place it gets a lot easier to create exactly the right mock for the scenario you want to test. The test becomes clearer, and to a certain extent you’ve abstracted your tests away from the specific mocking framework that you are using.
It’s not all ribbons and bows. One problem is that you have to actually build the fluent interface. You can’t really make a generic one of these. A fluent interface by it’s nature is a Domain Specific Language. You implement a language based on the properties of the objects you’ll be mocking.
Creating the Fluent Interface isn’t a particularly complicated task (see Listing 5), but it’s enough work that you need to think carefully about whether it will pay for itself. The example here is also artificially simple, showing only a few stub methods. When you get into creating a fluent interface that allows you to configure Mock behaviour, like verifying method calls etc, things could get a little hairy.
It’s worth looking more closely at the shaded code in Listing 5, we what appears to be a readonly property, modifying fields within the class. What madness is this? It’s nothing really, just a trick used in constructing fluent grammars to avoid having parenthesis after every term in a statement.
// Listing 5
public class MockWizardStep
{
private Mock<IWizardStep> _step;
private bool _thatCan = true;
public MockWizardStep()
{
_step = new Mock<IWizardStep>();
}
public MockWizardStep ThatCan
{
get
{
_thatCan = true;
return this;
}
}
public MockWizardStep ThatCannot
{
get
{
_thatCan = false;
return this;
}
}
public MockWizardStep MoveNext
{
get
{
_step.Setup(v => v.OKToMoveNext()).Returns(_thatCan);
return this;
}
}
public MockWizardStep MovePrevious
{
get
{
_step.Setup(v => v.OKToMovePrevious()).Returns(_thatCan);
return this;
}
}
public IWizardStep Object()
{
return _step.Object;
}
public Mock<IWizardStep> Mock()
{
return _step;
}
}
So, where does that leave us? Are mocking frameworks saved from those who would hate them? Well, probably not, but for everyone else here’s one more tool in your toolbox for that day when the perfect scenario presents itself.








Just spotted this now.
Not only am I three years behind the curve, but I even used the same title for my post.
http://blog.bittercoder.com/PermaLink,guid,d4663750-eb79-4d10-aae6-a2e459e7b0d6.aspx