I'm attempting to write a unit test for a class with JUnit and Mockito and in my testing, I've found that a method that I'm trying to stub is actually overloaded and has two definitions, one with 3 strings as an arg and returns an object, another with four strings and returns a list of the aforementioned object. I'm curious as to why matchers such as anyString() don't seem to successfully stub the method, while any() does.
Is there any way I can get more specific matchers to work, or am I stuck with using any() for overloaded methods?
An example of what I mean:
public String testedMethod(String s) {
//I want to mock this
return classObject.method(String first, String second, String third);
}
public class classObject {
public String method(String first, String second, String third) {
return "3 args";
}
public List<String> method(String first, String second, String third, String fourth) {
ArrayList<String> returned = new ArrayList<>();
returned.add("4 args");
return returned;
}
}
@Test
public void testClassMethod() {
//this doesn't work
//Mockito.when(classObject).method(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()).thenReturn("successful stub");
//this does work
Mockito.when(classObject).method(Mockito.any(), Mockito.any(), Mockito.any()).thenReturn("successful stub");
//only passes with the second mock
Assert.assertEquals("successful stub", testedClass.testedMethod("a string"));
}
Mockito.anyString() does not match null values, because null is not an instance of String.
You're most likely not able to mock the method when replacing any() with anyString() simply because one of the method arguments is actually null rather than a String.
More information on the topic: https://github.com/mockito/mockito/issues/185
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With