gpt4 book ai didi

mockito - 调用 when 方法时 powermock 出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-02 22:23:39 25 4
gpt4 key购买 nike

我似乎无法使用 powermock 模拟公共(public)函数调用的返回。

有人可以帮帮我吗?

失败的行是

PowerMockito.doReturn(aa).when(B.class, B.class.getDeclaredMethod("getA"));

特别是在“when”方法中

代码:

import static org.junit.Assert.fail;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
public class PowermockTest {

private static class A {

private int number;

public A(int number) {
this.number = number;
}

public int getNumber() {
return number;
}
}

private static class B {

private int number;
private A a;

public B(int number) {
this.number = number;
}

public A getA() {
if (a == null) {
a = new A(number);
}
return a;
}
}

@Test
public void testOdrService() {
A aa = PowerMockito.mock(A.class);
try {
B bb = new B(3);
PowerMockito.doReturn(aa).when(B.class, B.class.getDeclaredMethod("getA"));
} catch (Exception e) {
fail("Exception in test. " + e.getMessage());
}
}

}

附言:

将代码更改为以下工作但它强制创建我不想要的虚拟对象

B bb = new B(3);
B bb1 = PowerMockito.spy(bb);
PowerMockito.doReturn(aa).when(bb1).getA();
A mockedA = bb1.getA();

最佳答案

PowerMockito.doReturn(aa).when(B.class, B.class.getDeclaredMethod("getA"));

此语法专门用于 mocking static methods , 不是 mocking instance methodsgetA()

在大多数情况下,您不需要保留原始( spy )对象。直接与 spy 互动:

B bb = PowerMockito.spy(new B(3));
// work with bb as normal
PowerMockito.doReturn(aa).when(bb).getA();
A mockedA = bb.getA(); // mockedA == aa

关于mockito - 调用 when 方法时 powermock 出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13305177/

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