Is there a way to capture a list of specific type using mockitos ArgumentCaptore. This doesn\'t work:
ArgumentCaptor> argumen
There is an open issue in Mockito's GitHub about this exact problem.
I have found a simple workaround that does not force you to use annotations in your tests:
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
public final class MockitoCaptorExtensions {
public static ArgumentCaptor captorFor(final CaptorTypeReference argumentTypeReference) {
return new CaptorContainer().captor;
}
public static ArgumentCaptor captorFor(final Class argumentClass) {
return ArgumentCaptor.forClass(argumentClass);
}
public interface CaptorTypeReference {
static CaptorTypeReference genericType() {
return new CaptorTypeReference() {
};
}
default T nullOfGenericType() {
return null;
}
}
private static final class CaptorContainer {
@Captor
private ArgumentCaptor captor;
private CaptorContainer() {
MockitoAnnotations.initMocks(this);
}
}
}
What happens here is that we create a new class with the @Captor annotation and inject the captor into it. Then we just extract the captor and return it from our static method.
In your test you can use it like so:
ArgumentCaptor>>> fancyCaptor = captorFor(genericType());
Or with syntax that resembles Jackson's TypeReference:
ArgumentCaptor>>> fancyCaptor = captorFor(
new CaptorTypeReference>>>() {
}
);
It works, because Mockito doesn't actually need any type information (unlike serializers, for example).