簡體   English   中英

我無法使用Mockito和PowerMockito模擬靜態方法

[英]I can't mock static method using Mockito and PowerMockito

我在第三方庫中模擬靜態方法時遇到麻煩。 運行測試時,我一直收到空指針異常,但是我不確定為什么會這樣。

這是類和void方法,它們調用我嘗試模擬的“ MRClientFactory.createConsumer(props) ”的靜態方法:

public class Dmaap {

    Properties props = new Properties();
    public Dmaap() {

    }

    public MRConsumerResponse createDmaapConsumer() {
        System.out.println("at least made it here");
        MRConsumerResponse mrConsumerResponse = null;
        try {
            MRConsumer mrConsumer = MRClientFactory.createConsumer(props);
            System.out.println("made it here.");
            mrConsumerResponse = mrConsumer.fetchWithReturnConsumerResponse();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace(); 
        }

        return mrConsumerResponse;      
    }
}

下面是不斷返回空指針異常的測試。 生成空指針的特定行是: MRClientFactory.createConsumer(Mockito.any(Properties.class));

@RunWith(PowerMockRunner.class)
@PrepareForTest(fullyQualifiedNames = "com.vismark.PowerMock.*")
public class DmaapTest {

    @Test
    public void testCreateDmaapConsumer() {
        try {
            Properties props = new Properties();
            PowerMockito.mockStatic(MRClientFactory.class);

            PowerMockito.doNothing().when(MRClientFactory.class);

            MRClientFactory.createConsumer(Mockito.any(Properties.class));

            //MRClientFactory.createConsumer(props);

            Dmaap serverMatchCtrl = new Dmaap();
            Dmaap serverMatchCtrlSpy = spy(serverMatchCtrl);

            serverMatchCtrlSpy.createDmaapConsumer();

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

請仔細遵循以下示例: https : //github.com/powermock/powermock/wiki/MockStatic

特別是你錯過了

@PrepareForTest(Dmaap.class)

…表示執行靜態調用的類。

暫無
暫無

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

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