Tasty Test Tip: Using ArgumentCaptor for generic collections with Mockito
Mockito has a very nice feature that allows you to verify what parameters were used when a method was executed. For example:
ArgumentCaptor argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());
However, when using generic typed objects, some problems rise up. For example, the following won't work:
ArgumentCaptor\> argument = ArgumentCaptor.forClass(List.class);
This is obviously not a Mockito problem, but a generics problem. To solve this, follow these two steps:
use the @Captor annotation.
@Captor private ArgumentCaptor\> argumentCaptor;
initialize the Mockito annotations in your initialization method (add one if you don't have one)
@Before public void init(){ MockitoAnnotations.initMocks(this); }
And presto! You can now capture the parameters that were used when a to be verified method was executed.
verify(someMock).someMethod(argumentCaptor.capture());