我想模拟私有方法,它从我的测试方法调用,但不是模拟,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);
}
}
这是正常的情况吗?如果调用了mock方法有什么意义呢?
答案 0 :(得分:0)
要使用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);
}
}
答案 1 :(得分:0)
在这里,我将为我的未来自我留下第二个答案。这里还有另一个问题。如果要调用Static.method,请确保“方法”实际上是在Static中定义的,而不是在层次结构中。
在我的情况下,代码称为Static.method,但是Static是从StaticParent扩展的,而“ method”实际上是在StaticParent中定义的。
@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticParent.class)
public class YourTestClass {
@Before
public init() {
PowerMockito.mockStatic(StaticParent.class);
when(StaticParent.method("")).thenReturn(yourReturnValue);
}
}
public class ClassYoureTesting {
public someMethod() {
Static.method(""); // This returns yourReturnValue
}