Revisiting Mocks, Stubs, Dummies and Fakes

A discussion within my current team highlighted (or rather highlighted again) that many developers use the above terms almost synonymously. This of course leads to confusion and wasted time as we have to explain to each other what exactly we mean.

With the growing popularity of mocking frameworks like the superb Mockito, people are more likely to use Mock correctly but what about the others? It seemed like a good time to remind ourselves what we each meant.

As an obvious appeal to authority, I suggested that we use a post by Martin Fowler to base our definitions on (in something as subjective as best practice in programming using an expert as the basis of decsions – they might not always been completely correct but they are almost never wrong). Paraphrasing we end up with these:

Dummy objects are passed around but never actually used beyond preventing some failure like a NullPointerException. The value they return is completely unimportant. Usually they are just used to fill parameter lists in methods.

Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test. The classic usage of this is for services where you can create a Service Stub. Using a stub allows faster testing as well as pre-delivery integration where you only have the interface or API of an integration partner. The level of state or awareness of the Stub depends on your usage.

Fake objects are the most similar to fully featured objects in that they actually have working implementations, but usually take some shortcut which makes them not suitable for production. For example, using an in memory database like SQLite rather than Oracle or Sybase.

Mocks are objects pre-programmed with expectations which form a specification of the calls they are expected to receive. In the Java world mocks can be easily created using libraries like EasyMock, JMockit and Mockito. To add a little confusion it can be said that something like Mockito is actually a Test spy framework. This is because the main emphasis of the framework is not mocking but observing the behaviour of the object. However the ability to create an implementation of a class or interface within a single method or annotation makes this as much of a Mock as anything.

TDD power users may find themselves aghast that this still has to be explained but the reality is that there are many companies out there who aren’t the bleeding-edge full on users of Agile methodology and the confusion is genuine.

Sometimes I think that we should issue new starters with a glossary of terms covering this. Or even better, make them read Martin Fowler’s book ‘Patterns of Enterprise Application Architecture’ and his Bliki so that they can pick this up by themselves along with a whole lot more.