The term 'Mock Objects' has become a popular one to describe special case objects that mimic real objects for testing. Most language environments now have frameworks that make it easy to create mock objects. What's often not realized, however, is that mock objects are but one form of special case test object, one that enables a different style of testing.Mocking - huh?
This post series is not to explain / debate on mocking and stubbing test strategies. If you are interested in reading what mocks are, why to use them and so on, please refer to the following links :
- This article by Martin Fowler describing mocks, stubs their differences and test strategies.
- Mock Objects article on Wikipedia - an excellent starting point.
- MockObjects.com - A site dedicated to mock objects!
- Mocking libraries and comparison. What I've finally used and why
- Mocking of instance functions, in a thread safe manner
- Mocking of static functions, in a thread safe manner
- Mocking of static getInstance() / factory methods, in a thread safe manner
Mocking libraries and comparison
There are multiple library projects that offer mocking and stubbing functionality. The number of choices are overwhelming and its often difficult to decide what's the right one to choose. For starters, simple dynamic proxy or sub-classing "mockers" would be just fine. For advances usages, "mockers" with greater benefits - probably state maintenance, static mocking would be useful.
A comparison of currently available mock libraries can be found here :
- JMockit documentation recently hosted an exhaustive comparison matrix recently.
- A comparison by Vasily Sizov on his blog from March 2009.
- StackOverFlow.com users had this great discussion over mock library choices
Our initial set of candidates included EasyMock and Mockito. Though JMockit sounded very tempting, due to lack of documentation (about 4 months back - though its improved quite a lot now) we did not want to adopt it - or so we thought.
EasyMock and Mockito are both very easy to code to and it was a tough call which one to use. Finally, multiple team members got their hands dirty using the two libraries and we voted. The winner was Mockito - we simply loved its documentation (everything was just there) and the extensibility for mocking behaviors. I have been happily mocking using Mockito since then - here I have use and like about Mockit :
- unlike EasyMock, Mockito is not a "record-n-play" mocker. You mock out what is necessary, when it is necessary, make unit test API calls and then verify expectations - all on demand.
- behavior mocking is very simple, written like English sentences in code : when(BasicService.foo()).thenReturn(retval);
- throwing exceptions, tracking number of calls made was possible and easy
- the return values from mock methods can be customized using the API call parameters.
- verification of mocked behavior is easy. Though there is no auto-verification feature.