问题描述
我正在尝试使用 JUnit 和 Mockito 为一个类编写单元测试,在我的测试中,我发现我尝试存根的方法实际上已重载并且有两个定义,一个有 3 个字符串作为 arg 并返回一个对象,另一个具有四个字符串并返回上述对象的列表。我很好奇为什么像 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 third) {
return "3 args";
}
public List<String> method(String first,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
。