Reputation: 875
I have three methods like these ones:
public void method1(String str){
...
}
public void method1(String str, String str2, String str3){
...
}
public void method1(String str, String str2, Object[] objs, String str3){
...
}
I want to check in Mockito if any of these methods are invoked, so I've tried to use anyVararg Matcher:
verify(foo).method1(anyVararg());
but this doesn't compile "The method method1(String, String) in the type Errors is not applicable for the arguments (Object)"
I have two questions:
Thanks.
Upvotes: 13
Views: 4124
Reputation: 3213
You could do this by using an Answer
to increment a counter if any of the methods are called.
private Answer incrementCounter = new Answer() {
public Object answer(InvocationOnMock invocation) throws Throwable {
counter++;
return null;
}
};
Note that you need to stub all methods. A method's uniqueness is based on its signature and not just the method name. Two methods with the same name are still two different methods.
doAnswer(incrementCounter).when(mockObj.method1(anyString()));
doAnswer(incrementCounter).when(mockObj.method1(anyString(), anyString()));
doAnswer(incrementCounter).when(mockObj.method2(anyString()));
See documentation for doAnswer
here.
Upvotes: 9
Reputation: 1283
You can intercept all calls on object like in this answer: Mockito - intercept any method invocation on a mock and then put combine this with approach suggested by @Bozho:
private Answer incrementCounter = new Answer() {
public Object answer(InvocationOnMock invocation) throws Throwable {
if (invocation.getMethod().getName().eqauls("someMethid")) {
counter++;
}
return null;
}
};
VendorObject mockObj = mock(SomeClass.class, incrementCounter);
Note: if you provide other interceptor for any of this methods - default will not be invoked.
Upvotes: 0
Reputation: 299218
A vararg method has a signature like this:
public void myMethod(String ... arguments){}
None of your methods is a vararg method.
I don't know Mockito so I can't solve your problem for you, but there is no possible abstraction over all three of the above methods unless you use reflection, so I guess you will have to use separate cases for each of the above methods.
Upvotes: 2