Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I verify that one of two methods was called using Mockito?

Tags:

java

mockito

Suppose I have a class with two methods where I don't care which is called...

public class Foo {
    public String getProperty(String key) {
        return getProperty(key, null);
    }
    public String getProperty(String key, String defaultValue) {
        //...
    }
}

Both the below (from another class, still in my application) should pass my test:

public void thisShouldPass(String key) {
    // ...
    String theValue = foo.getProperty(key, "blah");
    // ...
}

public void thisShouldAlsoPass(String key) {
    // ...
    String theValue = foo.getProperty(key);
    if (theValue == null) {
        theValue = "blah";
    }
    // ...
}

I don't care which was called, I just want one of the two variants to be called.

In Mockito, I can generally do things like this:

Mockito.verify(foo, atLeastOnce()).getProperty(anyString());

Or:

Mockito.verify(foo, atLeastOnce()).getProperty(anyString(), anyString());

Is there a native way to say "verify either one or the other occurred at least once"?

Or do I have to do something as crude as:

try {
    Mockito.verify(foo, atLeastOnce()).getProperty(anyString());
} catch (AssertionError e) {
    Mockito.verify(foo, atLeastOnce()).getProperty(anyString(), anyString());
}
like image 538
Adam Burley Avatar asked Sep 28 '15 17:09

Adam Burley


People also ask

How do you verify a method called in Mockito?

Mockito verify() simple example It's the same as calling with times(1) argument with verify method. verify(mockList, times(1)). size(); If we want to make sure a method is called but we don't care about the argument, then we can use ArgumentMatchers with verify method.

What does verify method do in Mockito?

Verify in Mockito simply means that you want to check if a certain method of a mock object has been called by specific number of times. When doing verification that a method was called exactly once, then we use: verify(mockObject).

Does Mockito verify use equals?

Mockito verifies argument values in natural java style: by using an equals() method.


1 Answers

You could use atLeast(0) in combination with ArgumentCaptor:

ArgumentCaptor<String> propertyKeyCaptor = ArgumentCaptor.forClass(String.class);
Mockito.verify(foo, atLeast(0)).getProperty(propertyKeyCaptor.capture(), anyString());

ArgumentCaptor<String> propertyKeyCaptor2 = ArgumentCaptor.forClass(String.class);
Mockito.verify(foo, atLeast(0)).getProperty(propertyKeyCaptor2.capture());

List<String> propertyKeyValues = propertyKeyCaptor.getAllValues();
List<String> propertyKeyValues2 = propertyKeyCaptor2.getAllValues();

assertTrue(!propertyKeyValues.isEmpty() || !propertyKeyValues2.isEmpty()); //JUnit assert -- modify for whatever testing framework you're using
like image 106
ach Avatar answered Oct 11 '22 16:10

ach