我试图对使用JUnit4的方法进行单元测试。被测方法正在调用另一个私有方法,我想使用PowerMockito模拟它。
我的方法如下:
Class MyClass {
public List<String> myMethod(String name) throws IOException
{
... Few lines of code for setting variables
List<String> result = myPrivateMethod(a, b);
... Few more lines of code..
result.addAll(myPrivateMethod(c, d));
return result;
}
private List<String> myPrivateMethod(String a, String b) {
.....
}
}
我测试上述代码的单元测试方法如下:
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class TestClass {
@Test
public void testMyMethod() throws Exception {
MyClass myClass = PowerMockito.spy(new MyClass());
PowerMockito.doReturn(new ArrayList<String>(){{add("temp");}}).when(myClass, "myPrivateMethod", "a", "b");
List<String> list = myClass.myMethod("someName");
assertEquals(list.size(), 1);
}
}
我期望 PowerMockito.doReturn(new ArrayList(){{add(“temp”);}}))。when(myClass,“myPrivateMethod”,“a”,“b”); 返回大小为1的列表。我确认执行不会进入私有方法,但是我没有在List中添加一个值。
上面的单元测试代码有什么问题,为什么我得到null而不是PowerMockito.doReturn()方法中提到的填充List?
最佳答案
在您的测试中,您正在调用myMethod
,后者依次调用myPrivateMethod
两次,请参见:
List<String> result = myPrivateMethod(a, b);
...
result.addAll(myPrivateMethod(c, d));
但是您的测试仅模拟一次对
myPrivateMethod
的调用,因此流程如下所示:myMethod
-> myPrivateMethod
,其中参数为a, b
-此被模拟,并且myPrivateMethod
返回“temp” myMethod
-> myPrivateMethod
,其中参数为c, d
-此未被嘲笑,因此myPrivateMethod
被执行为了使该断言通过:
assertEquals(list.size(), 1);
,您需要重新进行测试以模拟对myPrivateMethod
的第二次调用。另外,对“返回null”的引用表明此处的when
块:.when(myClass, "myPrivateMethod", "a", "b")
与myMethod
中提供的实际参数不匹配。这是一个工作示例:
public class MyClass {
public List<String> myMethod(String name) throws IOException {
List<String> result = myPrivateMethod("a", "b");
result.addAll(myPrivateMethod("c", "d"));
return result;
}
private List<String> myPrivateMethod(String a, String b) {
List<String> r = new ArrayList<>();
r.add(a);
r.add(b);
return r;
}
}
@Test
public void testMyMethod() throws Exception {
MyClass myClass = PowerMockito.spy(new MyClass());
PowerMockito.doReturn(new ArrayList<String>(){{add("temp");}})
.when(myClass, "myPrivateMethod", "a", "b");
PowerMockito.doReturn(new ArrayList<String>())
.when(myClass, "myPrivateMethod", "c", "d");
List<String> list = myClass.myMethod("someName");
assertEquals(1, list.size());
assertEquals("temp", list.get(0));
}
上面的示例测试通过了以下内容: