0 0 0 0


How can I verify that a mocked method was not called at all - with any combination of parameters - using Mockito?

For example I have an object - myObject - that is using a second, mocked object - myMockedOtherObject - that has a method - someMethodOrOther(String parameter1, String parameter2).

I want to call myObject.myMethod() and verify that someMethodOrOther()doesn't get called - with any combination of parameters.


verify(myMockedOtherObject, never()).someMethodOrOther();

Except I can't do that, because someMethodOrOther() requires specific parameters to be supplied.

Best Answer:

You need to use argument matchers to do stuff like this. You supply an argument matcher to correspond to every parameter in your method, but you must make sure that you pick one that has the right type. All of the ones you are likely to need are listed at

Suppose your method is

public void myMethod(
    String text, int count, MyClass something, List<MyClass> someList) {
    // ...

Your verify statement might look like this.

verify(myMock, never()).myMethod(
    anyString(), anyInt(), any(MyClass.class), anyListOf(MyClass.class));

Some of the matchers that you're likely to need are -

  • anyInt(), anyLong(), anyShort(), anyBoolean(), anyByte(), anyChar(), anyFloat(), anyDouble() - These match either the primitive version or the object version of each of these types. In my example, I've used anyInt() to match an int, but it will also match an Integer.
  • any(XXX.class) - This will match any object type at all. In my example, I've used it to match a MyClass.
  • anyString() - This is an alternative way of writing any(String.class)
  • anyListOf(XXX.class), anySetOf(XXX.class), anyMapOf(XXX.class, XXX.class) - These are good for matching the standard generic collection types. In my example, I've used anyListOf to match the List<MyClass>.

There are a handful of others, and I strongly recommend having a brief skim through the Javadoc. But these are the ones that you are most likely to use with never().

Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs