簡體   English   中英

為什么 Powermockito 調用我的模擬方法?

[英]Why Powermockito invokes my mocked method?

我想模擬從我的測試方法調用的私有方法,但不是模擬,而是 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 為類啟用靜態或非公開模擬,應將該類添加到注釋@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 擴展而來的,而“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
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM