javaunit-testingjunitmockito

How to use ArgumentCaptor for stubbing?


In Mockito documentation and javadocs it says

It is recommended to use ArgumentCaptor with verification but not with stubbing.

but I don't understand how ArgumentCaptor can be used for stubbing. Can someone explain the above statement and show how ArgumentCaptor can be used for stubbing or provide a link that shows how it can be done?


Solution

  • Assuming the following method to test:

    public boolean doSomething(SomeClass arg);
    

    Mockito documentation says that you should not use captor in this way:

    when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
    assertThat(argumentCaptor.getValue(), equalTo(expected));
    

    Because you can just use matcher during stubbing:

    when(someObject.doSomething(eq(expected))).thenReturn(true);
    

    But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

    ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
    verify(someObject).doSomething(argumentCaptor.capture());
    assertThat(argumentCaptor.getValue(), equalTo(expected));