Using Mocks to Verify Interactions

[article]

into its role of AgeCalculator and have it play its part. In this context, it is like an actor from Candid Camera. The poor ClientDetailsValidator has no idea it's being duped.

Verify State When Appropriate
Some very experienced developers remain unconvinced about verifying interactions using mocks. Their position is - how an object talks to other objects is its own business and shouldn't be explicitly defined in a test method. Instead, the test should verify an object's state (or data) to ensure something happened.

I tend to use a mixture of both, and again the behavior vocabulary helps. For behavior that is best described in terms of interactions, I'll use mocks. For behavior that produces an output (say a calculation) I'll verify the result.

In general, if you look at a system as being made up of cooperating components (aka services or subsystems), then for the classes within an individual component I tend to verify interactions, and at the "edges" of a component or service--when there is some tangible effect on the outside world or a message being passed around--I will verify state.

Resources
The original paper on mocks, by Tim Mackinnon et al., is at www.connextra.com/aboutUs/mockobjects.pdf. A follow-up called "Mock Roles, Not Objects" was presented at OOPSLA 2004 and can be found at www.jmock.org/oopsla2004.pdf.

For mocking in Java, check out JMock and EasyMock. For .Net, NMock is at www.nmock.org.

About the author

Dan North's picture Dan North

Dan North is a senior consultant with ThoughtWorks, where he coaches development teams in agile software delivery and project automation. A programmer with fifteen years of delivery experience, Dan has published a number of articles and spoken at conferences on topics ranging from agile enablement to NLP.

AgileConnection is one of the growing communities of the TechWell network.

Featuring fresh, insightful stories, TechWell.com is the place to go for what is happening in software development and delivery.  Join the conversation now!

Upcoming Events

Nov 09
Nov 09
Apr 13
May 03