Andreas Köberle Andreas Köberle - 3 months ago 37
Java Question

How to capture a list of specific type with mockito

Is there a way to capture a list of specific type using mockitos ArgumentCaptore. This doesn't work:

ArgumentCaptor<ArrayList<SomeType>> argument = ArgumentCaptor.forClass(ArrayList.class);

Answer

The nested generics-problem can be avoided with the @Captor annotation:

@RunWith(MockitoJUnitRunner.class)
public class Test{

    @Mock
    private Service service;

    @Captor
    private ArgumentCaptor<ArrayList<SomeType>> captor;

    @Test 
    public void shouldDoStuffWithListValues() {
        //...
        verify(service).doStuff(captor.capture()));
    }
}
Comments