gpt4 book ai didi

java - 如何避免 Mockito 和 PowerMockito 之间的冲突?

转载 作者:行者123 更新时间:2023-11-29 09:29:41 25 4
gpt4 key购买 nike

我需要测试几个非常简单的类。第一个是 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 会在内部调用 protectedMethodanotherMethodanotherMethod 已经被调用过一次。

如果您删除对 newMethodanotherMethod 的调用,测试将正常运行。

关于java - 如何避免 Mockito 和 PowerMockito 之间的冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25329588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com