简体   繁体   中英

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

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.

eg:

myObject.doSomeStuff();

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

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

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 .

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

More Clear way of presenting the solution

import static org.mockito.Mockito.verify;

import static org.mockito.Mockito.never;

//Testing scenario

verify(mockObject, never()).someMethod(mockParam1, MockParam2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM