Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify whether one of three methods is invoked with mockito

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:

  1. How can I solve this?
  2. Is there any way to check if any of two methods are invoked? Imagine I have another mathods called method2 and method3. I'd like to check if any of them is invoked (but at least one).

Thanks.

like image 607
Juanillo Avatar asked Apr 08 '11 11:04

Juanillo


People also ask

How do you check whether a method is called in Mockito?

Mockito verify() method can be used to test number of method invocations too. We can test exact number of times, at least once, at least, at most number of invocation times for a mocked method. We can use verifyNoMoreInteractions() after all the verify() method calls to make sure everything is verified.

How do you know if mocked method called?

To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).

Which method in Mockito verifies that no interaction has happened with a mock in Java?

Mockito verifyZeroInteractions() method It verifies that no interaction has occurred on the given mocks. It also detects the invocations that have occurred before the test method, for example, in setup(), @Before method or the constructor.

How do you check if a method is called in Java?

While you can replace it with blank == true , which will work fine, it's unnecessary to use the == operator at all. Instead, use if (blank) to check if it is true, and if (! blank) to check if it is false.


1 Answers

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.

like image 98
z7sg Ѫ Avatar answered Jan 05 '23 03:01

z7sg Ѫ