T
- type of argumentpublic interface ArgumentMatcher<T>
For non-trivial method arguments used in stubbing or verification, you have following options (in no particular order):
Matchers.notNull()
. Some times it is better to have a simple test that works than
a complicated test that seem to work.
ArgumentCaptor
to capture the arguments and perform assertions on their state.
Useful when you need to verify the arguments. Captor is not useful if you need argument matching for stubbing.
Many times, this option leads to clean and readable tests with fine-grained validation of arguments.
ArgumentMatcher
interface
and passing the implementation to the Matchers.argThat(org.mockito.ArgumentMatcher<T>)
method.
This option is useful if custom matcher is needed for stubbing and can be reused a lot
MockitoHamcrest.argThat(org.hamcrest.Matcher)
Useful if you already have a hamcrest matcher. Reuse and win!
Implementations of this interface can be used with Matchers.argThat(org.mockito.ArgumentMatcher<T>)
method:
class ListOfTwoElements implements ArgumentMatcher<List> {
public boolean matches(Object list) {
return ((List) list).size() == 2;
}
}
List mock = mock(List.class);
when(mock.addAll(argThat(new ListOfTwoElements))).thenReturn(true);
mock.addAll(Arrays.asList("one", "two"));
verify(mock).addAll(argThat(new ListOfTwoElements()));
To keep it readable you can extract method, e.g:
verify(mock).addAll(argThat(new ListOfTwoElements()));
//becomes
verify(mock).addAll(listOfTwoElements());
Read more about other matchers in javadoc for Matchers
class
boolean matches(Object argument)
The method should never assert if the argument doesn't match. It should only return false.
The argument is not using generic type in order to force explicit casting in the implementation. This way it is easier to debug when incompatible arguments are passed to the matchers. You have to trust us on this one. //TODO SF make sure it makes sense to receive an Object here instead of T and document it.
See the example in the top level javadoc for ArgumentMatcher
argument
- the argument