How to verify mocked method not called with any combination of parameters using Mockito
JavaUnit TestingMockingMockitoJava Problem Overview
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.
e.g.:
myObject.doSomeStuff();
verify(myMockedOtherObject, never()).someMethodOrOther();
Except I can't do that, because someMethodOrOther()
requires specific parameters to be supplied.
Java Solutions
Solution 1 - Java
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 - Java
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 usedanyInt()
to match anint
, but it will also match anInteger
.any(XXX.class)
- This will match any object type at all. In my example, I've used it to match aMyClass
.anyString()
- This is an alternative way of writingany(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 usedanyListOf
to match theList<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()
.
Solution 3 - Java
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);