gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:06:55 26 4
gpt4 key购买 nike

我正在尝试使用 JUnit 和 Mockito 为一个类编写单元测试,在我的测试中,我发现我试图 stub 的方法实际上已重载并且有两个定义,一个有 3 个字符串作为参数并返回一个对象,另一个具有四个字符串并返回上述对象的列表。我很好奇为什么诸如 anyString() 之类的匹配器似乎没有成功地 stub 该方法,而 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

关于java - 像 anyString() 这样的 Mockito 特定匹配器似乎不适用于重载方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66231384/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com