【发布时间】:2014-10-09 09:01:47
【问题描述】:
我需要测试一些非常简单的类。第一个是Child类:
public class Child extends Parent {
public int newMethod() {
anotherMethod();
protectedMethod();
return protectedMethodWithIntAsResult();
}
public void anotherMethod() {
// method body no so important
}
}
比我有一个Parent 类:
public class Parent {
protected void protectedMethod() {
throw new RuntimeException("This method shouldn't be executed in child class!");
}
protected int protectedMethodWithIntAsResult() {
throw new RuntimeException("This method shouldn't be executed in child class!");
}
}
最后是我的单一测试方法的测试类:
@PrepareForTest({Child.class, Parent.class})
public class ChildTest extends PowerMockTestCase {
@Test
public void test() throws Exception {
/** Given **/
Child childSpy = PowerMockito.spy(new Child());
PowerMockito.doNothing().when(childSpy, "protectedMethod");
PowerMockito.doReturn(100500).when(childSpy, "protectedMethodWithIntAsResult");
/** When **/
int retrieved = childSpy.newMethod();
/** Than **/
Assert.assertTrue(retrieved == 100500);
Mockito.verify(childSpy, times(1)).protectedMethod();
Mockito.verify(childSpy, times(1)).protectedMethodWithIntAsResult();
Mockito.verify(childSpy, times(1)).anotherMethod(); // but method was invoked 3 times.
}
}
我上次验证有问题。程序抛出异常:
org.mockito.exceptions.verification.TooManyActualInvocations:
child.anotherMethod();
Wanted 1 time:
-> at my.project.ChildTest.test(ChildTest.java:30)
But was 3 times. Undesired invocation:
我不明白为什么。任何想法为什么会发生?
【问题讨论】:
-
我建议在被测类中模拟方法调用不是一个好的测试实践。您应该简单地验证预期结果和任何潜在的副作用。
-
你测试的哪一行是
30? -
Mockito.verify(childSpy, times(1)).anotherMethod(); -
尝试将系统输出放入
anotherMethod并在每个测试方法之后。这应该为您提供有关何时/如何调用anotherMethod的线索。让我们知道结果。 -
其实 anotherMethod() 调用成功了。而且它只打印了一次消息。
标签: java unit-testing testng mockito powermock