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);
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:

1. use the @Captor annotation.

private ArgumentCaptor> argumentCaptor;

2. initialize the Mockito annotations in your initialization method (add one if you don’t have one).

public void init(){

And presto! You can now capture the parameters that were used when a to be verified method was executed.


Leave a Reply

Your email address will not be published. Required fields are marked *