Another option is to rely on good old fashion equals
method. As long as the argument in the when
mock equals
the argument in the code being tested, then Mockito will match the mock.
Here is an example.
public class MyPojo {
public MyPojo( String someField ) {
this.someField = someField;
}
private String someField;
@Override
public boolean equals( Object o ) {
if ( this == o ) return true;
if ( o == null || getClass() != o.getClass() ) return false;
MyPojo myPojo = ( MyPojo ) o;
return someField.equals( myPojo.someField );
}
}
then, assuming you know what the value for someField
will be, you can mock it like this.
when(fooDao.getBar(new MyPojo(expectedSomeField))).thenReturn(myFoo);
pros: This is more explicit then any
matchers. As a reviewer of code, I keep an eye open for any
in the code junior developers write, as it glances over their code's logic to generate the appropriate object being passed.
con: Sometimes the field being passed to the object is a random ID. For this case you cannot easily construct the expected argument object in your mock code.
Another possible approach is to use Mockito's Answer
object that can be used with the when
method. Answer
lets you intercept the actual call and inspect the input argument and return a mock object. In the example below I am using any
to catch any request to the method being mocked. But then in the Answer
lambda, I can further inspect the Bazo argument... maybe to verify that a proper ID was passed to it. I prefer this over any
by itself so that at least some inspection is done on the argument.
Bar mockBar = //generate mock Bar.
when(fooDao.getBar(any(Bazo.class))
.thenAnswer( ( InvocationOnMock invocationOnMock) -> {
Bazo actualBazo = invocationOnMock.getArgument( 0 );
//inspect the actualBazo here and thrw exception if it does not meet your testing requirements.
return mockBar;
} );
So to sum it all up, I like relying on equals
(where the expected argument and actual argument should be equal to each other) and if equals is not possible (due to not being able to predict the actual argument's state), I'll resort to Answer
to inspect the argument.