Mockito provides a Matcher<T>
interface along with an abstract ArgumentMatcher<T>
class to verify arguments. It uses a different approach to the same use-case than the ArgumentCaptor
. Additionally the ArgumentMatcher can be used in mocking too. Both use-cases make use of the Mockito.argThat()
method that provides a reasonably readable test code.
verify(someMock).someMethod(Mockito.argThat(new ArgumentMatcher<String>() {
@Override
public boolean matches(Object o) {
return o instanceof String && !((String)o).isEmpty();
}
});
From the JavaDocs of ArgumentMatcher:
Warning: Be reasonable with using complicated argument matching, especially custom argument matchers, as it can make the test less readable. Sometimes it's better to implement equals() for arguments that are passed to mocks (Mockito naturally uses equals() for argument matching). This can make the test cleaner.