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"));
}