我需要测试一些非常简单的类。第一个是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:
而且我不明白为什么。任何想法为什么会发生?
最佳答案
当您调用int retrieved = childSpy.newMethod()
时会发生问题,因为在那里您正在调用anotherMethod()
和protectedMethod()
。
Mockito假定您将只调用每个方法,但是newMethod
内部调用protectedMethod
和anotherMethod
,并且anotherMethod
已被调用一次。
如果删除对newMethod
或anotherMethod
的调用,测试将正常进行。