关于java:为什么Powermockito会调用我的模拟方法?

Why Powermockito invokes my mocked method?

我想模拟私有方法,它从我的测试方法调用,但不是模拟,PowerMockito调用toMockMethod,我得到NPE。
toMockMethod属于同一个类。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@RunWith(PowerMockRunner.class)
public class PaymentServiceImplTest {

    private IPaymentService paymentService;

    @Before
    public void init() {
        paymentService = PowerMockito.spy(Whitebox.newInstance
                (PaymentServiceImpl.class));
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
        ...
        PowerMockito.doReturn(mockedReturn)
                .when(paymentService,
                     "toMockMethod",
                      arg1, arg2);
    }
}

这是正常的情况吗? 如果调用了mock方法有什么意义呢?


要使用PowerMock为类启用静态或非公共模拟,应将该类添加到注释@PrepareForTest。 在你的情况下,它应该是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@RunWith(PowerMockRunner.class)
@PrepareForTest(PaymentServiceImpl.class)
public class PaymentServiceImplTest {

    private IPaymentService paymentService;

    @Before
    public void init() {
        paymentService = PowerMockito.spy(Whitebox.newInstance
                (PaymentServiceImpl.class));
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
        ...
        PowerMockito.doReturn(mockedReturn)
                .when(paymentService,
                     "toMockMethod",
                      arg1, arg2);
    }
}