Java 为什么Powermockito调用我的模拟方法?
我想模拟从我的测试方法调用的私有方法,但不是模拟,而是PowerMockito调用toMockMethod,我得到了NPE。 toMockMethod在同一个类中Java 为什么Powermockito调用我的模拟方法?,java,junit4,powermockito,Java,Junit4,Powermockito,我想模拟从我的测试方法调用的私有方法,但不是模拟,而是PowerMockito调用toMockMethod,我得到了NPE。 toMockMethod在同一个类中 @RunWith(PowerMockRunner.class) public class PaymentServiceImplTest { private IPaymentService paymentService; @Before public void init() { payment
@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
。在您的情况下,它应该是:
@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);
}
}
我要给我未来的自己留下第二个答案。这里还有另一个问题。如果要调用Static.method,请确保“method”实际上是在Static中定义的,而不是在层次结构上定义的 在我的例子中,代码名为Static.method,但Static是从StaticParent扩展而来的,“method”实际上是在StaticParent中定义的
@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticParent.class)
公共类YourTestClass{
@以前
公共init(){
mockStatic(StaticParent.class);
when(StaticParent.method(“”)。thenReturn(yourReturnValue);
}
}
公共类ClassYourTest{
公共方法(){
Static.method(“”;//返回您的returnValue
}
当您想测试服务时,通常会模拟其与私有方法交互的依赖项,而不是模拟私有方法。@Compass我测试一个公共方法,该方法调用同一类的私有方法请参见