How to verify mocked method not called with any combination of parameters using Mockito

Solution 1:

You can accomplish what you want with Mockito's argument matchers:

myObject.doSomeStuff();

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

You can make that a little less verbose with a static import like you have for verify and never.

Solution 2:

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 http://docs.mockito.googlecode.com/hg/latest/org/mockito/Matchers.html.

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().