【发布时间】:2015-02-11 08:44:46
【问题描述】:
我需要使用 TestNG、Mockito 和现在的 PowerMockito 针对预先存在的代码库编写单元测试,以便更轻松地测试私有和静态方法。我目前正在尝试针对我们正在测试的类中的私有 void 方法编写测试,但无法弄清楚。在普通的 PowerMock API 中有称为 replayAll()、verifyAll() 和 expectLastCalled() 的方法,它们适用于大多数用途。我只是找不到好的文档来解释如何以 PowerMockito 方式进行操作。对此的任何解释或见解将不胜感激。
测试方法:
private void pVMethod(Type param) throws Exception {
param.setA(StaticClass.methodA().toString());
param.setB(StaticClass.methodB().toString());
// getMemo(String label) is in a public class in same package
param.setC(getMemo("memo.provider"));
param.setD(getMemo("memo.item"));
try {
param.setTimestamp(DataTypeFactory.newInstance().newXMLGregorianCalendar(newjava.util.GregorianCalendar()));
} catch (SomeException e) {
...
throw new Exception();
}
}
测试尝试:
@Test(expectedExceptions = Exception.class)
public void pVMethod() throws Exception {
TestClass testMock = mock(TestClass.class);
Exception exception = mock(Exception.class);
// StaticClass staticClassMock = mock(StaticClass.class); ??
mockStatic(StaticClass.class);
// when(..) and thenReturn(..) are static imports from PowerMockito library
when(StaticClass.methodA()).thenReturn("stubStringA");
when(StaticClass.methodB()).thenReturn("stubStringB");
doThrow(exception).when(param).setTimestamp(Mockito.any(XMLGregorianCalendar.class));
// Docs say method name can be inferred via reflection
Whitebox.invokeMethod(tested, event);
// this is where things are hairy. testedSpy is defined at the top level
verifyPrivate(testedSpy).pVMethod(testMock);
}
【问题讨论】:
-
有点跑题了,但是为什么你要测试私有方法?单元测试应该测试功能,而不是实现
-
我的主管告诉我这样做。我是这种规模的测试新手,我真的不知道为什么会或不会这样做。但我可以说,powermock 是为了满足测试私有和静态方法/字段等的需求,否则这些方法是无法访问的。
-
如果您提供更多上下文可能会有所帮助。 有一些测试私有方法的正当理由,但是如果没有全貌,就很难给出建议
-
你的主管是个傻瓜。无需测试私有方法。而是测试公共、受保护和包访问方法,私有方法将被覆盖。
-
哈,好的。我会和他谈谈。但是尝试验证是否调用了私有 void 方法是不合理的吗?即为什么有一个名为“verifyPrivate()”的方法以及使用它的正确方法是什么?
标签: java unit-testing testng mockito powermock