当方法时调用powermock中的nullpoInterException



我似乎无法使用PowerMock模拟公共功能调用的返回。

有人可以帮我吗?

失败线是

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());
        }
    }
}

PS:

将代码更改为以下作品,但它迫使我不想要的虚拟对象的创建

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"));

此语法专门用于模拟静态方法,而不是模拟诸如getA()的实例方法。

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

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

相关内容

  • 没有找到相关文章