像 anyString() 这样的 Mockito 特定匹配器似乎不适用于重载方法?

Mockito specific matchers like anyString() don't seem to work with overloaded methods?

我正在尝试使用 JUnit 和 Mockito 为 class 编写单元测试,在我的测试中,我发现我尝试存根的方法实际上已超载并且有两个定义,一个有 3 个字符串作为 arg 和 returns 一个对象,另一个有四个字符串和 returns 上述对象的列表。我很好奇为什么像 anyString() 这样的匹配器似乎没有成功地存根该方法,而 any() 却可以。

有什么方法可以让更具体的匹配器工作,还是我坚持使用 any() 来重载方法?

我的意思的一个例子:

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() 不匹配 null 值,因为 null 不是 String.

的实例

在将 any() 替换为 anyString() 时,您很可能无法模拟该方法,因为方法参数之一实际上是 null 而不是 String.

有关该主题的更多信息:https://github.com/mockito/mockito/issues/185