Mocking with ease using mockito

I have been using mock objects for a very long time now. I started back in the day of EasyMock 1.x. This was a great help when removing the extra complexity of an enterprise server and the libraries it used when creating unit tests. And EasyMock has evolved tremendously since then. I followed this development closely using it for several year.

However, about two years back a colleague of mine suggested I try out something new. A mocking framework that tasted as good as a well shaken cocktail. The idea spoke to me. So I decided to try out mockito.

I have never turned back since. Mockito offers a very simple way to create and verify mocks. It is transparent to if I am mocking classes or interfaces. And it provides a readable easy to use API.

I find that I mock away far more boilerplate code in my tests now then I ever used to do with EasyMock. This is since Mockito provides the flexibility to only verify the methods calls that needs to be verified and will not reports errors on methods calls that are not recorded unless told otherwise. This makes it easy to mock away even value objects and data transfer objects when this makes the tests easer to read.

To create a mock object without recoded behaviour three lines of code is required. Annotate the class with @RunWith(MockitoJUnitRunner.class). Create a field for the mock object with an annotation to define that it is a mock:

That's it, it's ready to use. And any call to it will succeed unless specific behaviour is needed.

Mockito also has support for BDD like syntax with the BBDMock class. Since I use given-when-then as a way to create readable tests this is a great help.

The framework is also available for Python, Flex, Javascript, Scala and Perl. The list with links can be found here. How good the frameworks are for those languages I don't know. If you do I would be interested to hear.

  • Registered nurse

    Great site. A lot of useful information here. I’m sending it to some friends!