Java – Mockito: Stub method with complex object as a parameter

javamockitoparametersstub

Maybe this is a newbie question, but can't find the answer.

I need to stub a method with Mockito. If the method has "simple" arguments, then I can do it. For example, a find method with two parameters, car color and number of doors:

 when(carFinderMock.find(eq(Color.RED),anyInt())).thenReturn(Car1);
 when(carFinderMock.find(eq(Color.BLUE),anyInt())).thenReturn(Car2);
 when(carFinderMock.find(eq(Color.GREEN), eq(5))).thenReturn(Car3);

The problem is that the find argument is a complex object.

 mappingFilter = new MappingFilter();
 mappingFilter.setColor(eq(Color.RED));
 mappingFilter.setDoorNumber(anyInt());
 when(carFinderMock.find(mappingFilter)).thenReturn(Car1);

This code does not work. The error is "Invalid use of argument matchers! 1 matchers expected, 2 recorded".

Can't modify the "find" method, it needs to be a MappingFilter parameter.

I suppose that I have to do "something" to indicate Mockito that when the mappingFilter.getColor is RED, and mappingFilter.getDoorNumber is any, then it has to return Car1 (and the same for the other two sentences).
But how?

Best Answer

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.
    }
}