What's the difference between Mockito Matchers isA, any, eq, and same?
any()
checks absolutely nothing. In Mockito 1.x,any(T.class)
also checks absolutely nothing but also saves you a cast (prior to Java 8).This is due to change in Mockito 2.0 and beyond, when
any(T.class)
will shareisA
semantics to mean "anyT
" or properly "any instance of typeT
".any()
will still check absolutely nothing.isA(T.class)
checks that the argumentinstanceof T
, implying it is non-null.same(obj)
checks that the argument is the same instance asobj
, such thatarg == obj
is true.eq(obj)
checks that the argument equalsobj
according to itsequals
method. This is also the behavior if you pass in real values without using matchers.Note that unless
equals
is overridden, you'll see the default Object.equals implementation, which would have the same behavior assame(obj)
.
If you need more exact customization, you can use an adapter for your own predicate:
- For Mockito 1.x, use
argThat
with a custom HamcrestMatcher<T>
that selects exactly the objects you need. - For Mockito 2.0 and beyond, use
Matchers.argThat
with a customorg.mockito.ArgumentMatcher<T>
, orMockitoHamcrest.argThat
with a custom HamcrestMatcher<T>
.
If your Request.class implements equals, then you can use eq():
Bar bar = getBar();
when(fooService.fooFxn(eq(bar)).then...
The above when would activate on
fooService.fooFxn(otherBar);
if
otherBar.equals(bar);
Alternatively, if you want to the mock to work for some other subset of input (for instance, all Bars with Bar.getBarLength()>10), you could create a Matcher. I don't see this pattern too often, so usually I create the Matcher as a private class:
private static class BarMatcher extends BaseMatcher<Bar>{
...//constructors, descriptions, etc.
public boolean matches(Object otherBar){
//Checks, casts, etc.
return otherBar.getBarLength()>10;
}
}
You would then use this matcher as follows:
when(fooService.fooFxn(argThat(new BarMatcher())).then...
Hope that helps!