a little madness

A man needs a little madness, or else he never dares cut the rope and be free -Nikos Kazantzakis


Easier Stubbing With Mockito

Ever need to stub just a method or two of some interface to nicely isolate a unit to test? In the past I have used classic mock object libraries to help, but these suffered from a few problems:

  1. The use of strings to specify method names to stub, which breaks refactoring.
  2. Awkward syntax to specify parameter values to match.
  3. Compulsory verification of the order and number of calls to the stub.

Some time ago EasyMock came along and solved the first two problems. By using a new record-replay interface for defining expected calls, EasyMock tests were both more intuitive and more maintainable. However the third problem remained: sometimes I just want to stub the methods, and not verify that they are called in any specific order or number of times. Some contraints can be relaxed with EasyMock but it always seemed a pain to do extra work when I just wanted the library to do less!

Well, last week I discovered Mockito, a more recent library inspired in part by EasyMock. The difference with Mockito is that stubbing and verification are separated. Instead of recording expectations, you:

  1. Stub the methods of interest.
  2. Run your test.
  3. Selectively verify the calls to your stub as you choose.

This separation works brilliantly when you don’t want to verify everything by default. When the test is unconcerned with exactly how the stub is called, there is no need to verify at all.

You can read more about how Mockito came about on the author’s blog. I highly recommend checking it out!

Liked this post? Share it!

Leave a Reply