我不能使用Mockito和PowerMockito来模拟静态方法

时间:2018-03-26 19:14:03

标签: java junit mockito powermock

我在第三方库中模拟静态方法时遇到问题。我在运行测试时一直收到空指针异常,但我不确定为什么会这样。

这是调用静态方法的类和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();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

请仔细遵循此示例:https://github.com/powermock/powermock/wiki/MockStatic

特别是你错过了

@PrepareForTest(Dmaap.class)

...表示执行静态调用的类。