调用when方法时powermock中的NullPointerException

Ade*_*ros 2 mockito powermock

我似乎无法模拟使用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());
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

PS:

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

B bb = new B(3);
B bb1 = PowerMockito.spy(bb);
PowerMockito.doReturn(aa).when(bb1).getA();
A mockedA = bb1.getA();
Run Code Online (Sandbox Code Playgroud)

Jef*_*ica 5

PowerMockito.doReturn(aa).when(B.class, B.class.getDeclaredMethod("getA"));
Run Code Online (Sandbox Code Playgroud)

这句法是专门为嘲讽静态方法,而不是嘲笑实例方法一样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
Run Code Online (Sandbox Code Playgroud)

  • 快速说明:Jeff提供的`when()`方法的文档在这里:http://docs.mockito.googlecode.com/hg/latest/org/mockito/stubbing/Stubber.html#when(T).旁注:我确信以上内容是为了发布而简化,但似乎没有任何内容需要PowerMockito而不是普通的Mockito. (2认同)