Monday, March 08, 2010

New annotations in mockito 1.8.3

Mockito 1.8.3 was recently released and I got a chance to use it today. There are a couple of new annotations available in this release: @Captor, @Spy, and @InjectMocks. I was able to use @Captor and @InjectMocks today. Even after just a few minutes with these two annotations, I'm sold. Very cool enhancement. I spent some quality time with EasyMock last week, and there's nothing easy with EasyMock. Ugh!! If you're hip to using mock objects in your Java unit testing efforts, you really should look at mockito these days. Details about @Captor and @InjectMocks follows.


This annotation will automatically create typed argument captors (org.mockito.ArgumentCaptor<T>) in your unit tests. Argument captors are essential in verifying indirect outputs to your mocked collaborators.

public class Test{
@Captor ArgumentCaptor<Foobar> foobarCaptor;

public void init(){

public void shouldDoSomethingUseful() {
Foobar capturedFoobar = foobarCaptor.getValue();
assertEquals("foobar", capturedFoobar.getName());


Automatically injects mocks by type using setter injection. Constructor injection is not currently available, but if you want to provide a patch, the mockito team will gladly consider your contribution. I'm actually more interested in reflection-based injection, similar to what Spring uses when annotating dependency fields using @Autowired. Having your unit tests inject dependencies via reflection would help me avoid the set* methods on the implementations. I may have to play with this a bit.

public class FooBarManagerTests {

@Mock private FooDependency mockFoo;
@Mock private BarDependency mockBar;
@InjectMocks private FooBarManager manager = new FooBarManagerImpl();

public void initMocks() {
// Initializes all mocks and then injects those mocks into the FooManager instance.

public void shouldDoSomething() {