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:
- The use of strings to specify method names to stub, which breaks refactoring.
- Awkward syntax to specify parameter values to match.
- 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:
- Stub the methods of interest.
- Run your test.
- 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!
This entry was posted on Thursday, June 12th, 2008 at 3:37 am and is filed under Agile, Continuous Integration, Technology, Testing. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.