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?
ArgumentCaptor allows us to capture an argument passed to a method to inspect it. This is especially useful when we can't access the argument outside of the method we'd like to test.
We can use @Captor annotation to create argument captor at field level.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With