我想模拟私有(private)方法,它从我的测试方法中调用,但 PowerMockito 不是模拟,而是调用 toMockMethod,然后我得到了 NPE。 toMockMethod 位于同一个类中。
@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);
}
}
这是正常情况吗?如果方法已被调用,那么模拟方法有什么意义?
最佳答案
要使用 PowerMock 对类启用静态或非公共(public)模拟,应将该类添加到注释 @PrepareForTest
中。在你的情况下,它应该是:
@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);
}
}
关于java - 为什么 Powermockito 调用我的模拟方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47077722/