使用PowerMockito 1.6验证静态方法调用


问题内容

我正在为类似于以下示例的方法编写JUnit测试用例:

Class SampleA{
    public static void methodA(){
        boolean isSuccessful = methodB();
        if(isSuccessful){
            SampleB.methodC();
        }
    }

    public static boolean methodB(){
        //some logic
        return true;
    }
}

Class SampleB{
    public static void methodC(){
        return;
    }
}

我在测试类中编写了以下测试用例:

@Test
public void testMethodA_1(){
    PowerMockito.mockStatic(SampleA.class,SampleB.class);

    PowerMockito.when(SampleA.methodB()).thenReturn(true);
    PowerMockito.doNothing().when(SampleB.class,"methodC");

    PowerMockito.doCallRealMethod().when(SampleA.class,"methodA");
    SampleA.methodA();
}

现在,我想验证是否调用了Sample Sample类的static methodC()。如何使用PowerMockito
1.6实现?我已经尝试了很多东西,但是似乎对我来说没有用。任何帮助表示赞赏。


问题答案:

就我个人而言,我不得不说PowerMock等是您的代码不错的情况下不应该解决的问题的解决方案。在某些情况下,这是必需的,因为框架等使用的静态方法会导致无法通过其他方式测试的代码,但是如果是关于您的代码的,则应始终偏向于重构而不是静态模拟。

无论如何,验证PowerMockito中的内容并不难…

PowerMockito.verifyStatic( Mockito.times(1)); // Verify that the following mock method was called exactly 1 time
SampleB.methodC();

(当然,要使其正常工作,必须将SampleB添加到@PrepareForTest注释中并对其进行调用mockStatic。)