为什么 Powermockito 调用我模拟的方法?

Why Powermockito invokes my mocked method?

我想模拟从我的测试方法调用的私有方法,但不是模拟,而是 PowerMockito 调用 toMockMethod,我得到了 NPE。 toMockMethod 在同一个 class.

@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 为 class 启用静态或非 public 模拟,应将 class 添加到注释 @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,请确保“方法”实际上是在静态中定义的,而不是在层次结构中。

在我的例子中,代码称为 Static.method,但 Static 扩展自 StaticParent,而“方法”实际上是在 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
    }