Mocking the proud

A mocking framework such as JMock provides a way of specifying and checking the interactions between an object under test and its collaborators, without having a full implementation of those collaborators to hand. However some prideful classes don’t like being mocked!

Initially, when all we have is an interface specifying the contract that some collaborator must fulfil, the mock objects created by the framework act as stubs for implementation code that has yet to be written. Later on, however, we use mock objects as replacements for actually existing implementations, so that we can unit test an object that drives other parts of a larger system without having to come up with a complex test configuration for the system itself.

In both cases, mocking allows us to pretend that the object under test has a fully functioning environment to interact with, when in fact it is in the position of a “brain in a vat” being fed artificial stimuli by the testing code.

User:Кирилл Мартынов [GFDL (http://www.gnu.org/copyleft/fdl.html) or CC-BY-SA-3.0-2.5-2.0-1.0 (www.creativecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons

In the usual case, a mock object fills out some entirely abstract interface: by default, JMock will complain if you try to mock a concrete class. Although with a bit of persuasion JMock is able (thanks to some cunning bytecode manipulation) to create mock implementations even of final classes, I’d argue that whenever you find yourself having to do this you have a prideful class and should consider it as a potential code smell.

Prideful classes are a particular problem when they show up at the public boundary of a system (e.g. as part of its API). Objects under unit test should ideally interact with the wider system through collaborators on that boundary ,rather than “reaching in” to work with internal system objects, in violation of the Law of Demeter.

So when you find you have to mock out an interface that a) belongs on the external boundary of some part of the system, and b) can’t be mocked without bytecode manipulation, because it’s tied to a specific implementation, alarm bells should go off in your head – separate modules within the system are in danger of becoming tightly and inflexibly coupled.

In this situation, consider humbling the proud by refactoring prideful classes to extract an abstract interface, which can be mocked freely.