Mockito 1.5 spies on plain objects
Mockito is a mocking framework for Java. It's very similar to EasyMock and jMock, but eliminates the need for expectations by verifying what has been called after execution. Other mocking libraries require you to record expectations before execution, which tends to result in ugly setup code.
Lack of expectations is a big win, as software developer Hamlet D'Arcy, a Mockito user, explains on his blog:
"Mockito really cleans up the unit test by not requiring expectations. Personally, I much prefer the Mockito API to the EasyMock API for that reason."
Ketan Padegaonkar at ThoughtWorks lavishes praise on Mockito's unique syntax too:
"This looks, and reads far better than the JMock syntax, and it was love at first sight; I'm test-infested now."
The 1.5 release of Mockito introduces the ability to "spy" on non-mock objects by verifying that certain methods get called on them. For example:
List list = new LinkedList();
List spy = spy(list);
Our "spy" variable now acts as a handle to the list object. It can be treated just like a mock object. For example, the size method can be stubbed out:
Normal methods can also be called and verified:
Another improvement is an alternate, more readable stubbing syntax. For example:
Can now be written as:
This is the same length as the old style, but reads more cleanly and has fewer parenthesis. In addition to
doReturn(), there are also
Other useful features of Mockito include:
- Ability to mock concrete classes and interfaces
- Custom argument matchers
- Ordered verification
- Clean stack traces
Getting started with Mockito is as simple as adding a JAR file to your classpath. Visit the Google Code project for installation instructions, documentation, and more code samples.
It's good to see proper support for Test Spies
InfoQ Sep 01, 2015