What's the difference between Mockito Matchers isA, any, eq, and same?

倖福魔咒の 提交于 2019-11-28 05:46:11
Jeff Bowman
  • 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 share isA semantics to mean "any T" or properly "any instance of type T". any() will still check absolutely nothing.

  • isA(T.class) checks that the argument instanceof T, implying it is non-null.

  • same(obj) checks that the argument is the same instance as obj, such that arg == obj is true.

  • eq(obj) checks that the argument equals obj according to its equals 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 as same(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 Hamcrest Matcher<T> that selects exactly the objects you need.
  • For Mockito 2.0 and beyond, use Matchers.argThat with a custom org.mockito.ArgumentMatcher<T>, or MockitoHamcrest.argThat with a custom Hamcrest Matcher<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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!