Class to be tested
public class ClassUnderTest {
public void functionA() {
functionB();
functionC();
}
private void functionB() {
}
private void functionC() {
}
}
测试类
@RunWith(PowerMockRunner.class)
public class TestClass {
@Test
public void testFunctionA() throws Exception {
ClassUnderTest classUnderTest = PowerMockito.spy(new ClassUnderTest());
classUnderTest.functionA();
PowerMockito.verifyPrivate(classUnderTest).invoke("functionB");
PowerMockito.verifyPrivate(classUnderTest).invoke("functionC");
}
}
执行测试类时,我收到以下错误,
org.mockito.exceptions.misusing.UnfinishedVerificationException:
Missing method call for verify(mock) here:
-> at org.powermock.api.mockito.PowerMockito.verifyPrivate(PowerMockito.java:312)
Example of correct verification:
verify(mock).doSomething()
Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
如果评论了一个验证,那么测试用例就可以了。
答案 0 :(得分:3)
您必须在PrepareForTest中添加ClassUnderTest。
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassUnderTest.class)
public class TestClass {
@Test
public void testFunctionA() throws Exception {
ClassUnderTest classUnderTest = PowerMockito.spy(new ClassUnderTest());
classUnderTest.functionA();
PowerMockito.verifyPrivate(classUnderTest).invoke("functionB");
PowerMockito.verifyPrivate(classUnderTest).invoke("functionC");
}
我刚刚在私有方法中添加了sysouts&运行测试类。
答案 1 :(得分:0)
另一个想法是:不要这样做。 不 验证私有方法。出于某种原因,这些方法是私有。您应该尽量避免编写必须知道调用某些私有方法的测试。
你知道,私人的想法是:它可能会发生变化。一个好的单元测试与观察你的类的行为一起工作 - 你用不同的参数调用公共方法;并检查结果返回。或者,您可以使用依赖注入为测试类提供模拟对象 - 当您的测试代码需要其他方法来完成其工作时。
但你应该不开始检查私有方法。关键是:那些私有方法应该做一些从外部可以观察到的东西。他们要么在决赛中工作,要么回归"值;或者他们改变一些可能以其他方式检查的内部状态。换句话说:如果那些私有方法不会对你所测试的类造成任何其他影响 - 无论如何它们的目的是什么?!
答案 2 :(得分:0)
您可以尝试添加两行代码
@RunWith(PowerMockRunner.class)
public class TestClass {
@Test
public void testFunctionA() throws Exception {
ClassUnderTest classUnderTest = PowerMockito.spy(new ClassUnderTest());
PowerMockito.doNothing().when(classUnderTest, "functionB");
PowerMockito.doNothing().when(classUnderTest, "functionC");
classUnderTest.functionA();
PowerMockito.verifyPrivate(classUnderTest).invoke("functionB");
PowerMockito.verifyPrivate(classUnderTest).invoke("functionC");
}
}