Mockito: Stub method with complex object as a parameter
Use a Hamcrest matcher, as shown in the documentation:
when(carFinderMock.find(argThat(isRed()))).thenReturn(car1);
where isRed()
is defined as
private Matcher<MappingFilter> isRed() {
return new BaseMatcher<MappingFilter>() {
// TODO implement abstract methods. matches() should check that the filter is RED.
}
}
Since 2.1.0 Mockito has its own matcher mechanism build on top of org.mockito.ArgumentMatcher
interface. This allows to avoid using Hamcrest. Usage is almost of same as with Hamcrest. Keep in mind that ArgumentMatcher
is a functional interface and implementation of a matched can be expressed as a lambda expression.
private ArgumentMatcher<SomeObject> isYellow() {
return argument -> argument.isYellow();
}
and then
when(mock.someMethod(argThat(isYellow()).thenReturn("Hurray");