简体   繁体   English

我无法使用Mockito和PowerMockito模拟静态方法

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

I'm having trouble mocking a static method in a third-party library. 我在第三方库中模拟静态方法时遇到麻烦。 I keep receiving a null-pointer exception when running the test, but I'm not sure why that is. 运行测试时,我一直收到空指针异常,但是我不确定为什么会这样。

Here is the class and the void method that invokes the static method I'm trying to mock " MRClientFactory.createConsumer(props) ": 这是类和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;      
    }
}

Below is the test that keeps returning a null-pointer exception. 下面是不断返回空指针异常的测试。 The specific line where the null-pointer is being generated is: MRClientFactory.createConsumer(Mockito.any(Properties.class)); 生成空指针的特定行是: 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();
        }
    }

}

Please follow this example carefully: https://github.com/powermock/powermock/wiki/MockStatic 请仔细遵循以下示例: https : //github.com/powermock/powermock/wiki/MockStatic

Especially you are missing a 特别是你错过了

@PrepareForTest(Dmaap.class)

…to denote the class which does the static call. …表示执行静态调用的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM