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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34323909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:45:24  来源:igfitidea点击:

Verify Static Method Call using PowerMockito 1.6

javamockitojunit4powermockpowermockito

提问by Prerak Tiwari

I am writing JUnit test case for methods similar to sample given below:

我正在为类似于下面给出的示例的方法编写 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;
    }
}

I wrote the following test case in my test class:

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

@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();
}

Now I want to verify whether static methodC() of class Sample B is called or not. How can I achieve using PowerMockito 1.6? I have tried many things but it doesn't seems to be working out for me. Any help is appreciated.

现在我想验证是否调用了类 Sample B 的静态 methodC() 。如何使用 PowerMockito 1.6 实现?我尝试了很多东西,但似乎对我不起作用。任何帮助表示赞赏。

回答by Florian Schaetz

Personally, I have to say that PowerMock, etc. is the solution to a problem that you shouldn't have if your code wasn't bad. In some cases, it is required because frameworks, etc. use static methods that lead to code that simply cannot be tested otherwise, but if it's about YOUR code, you should always prefer refactoring instead of static mocking.

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

Anyway, verifing that in PowerMockito shouldn't be that hard...

无论如何,在 PowerMockito 中验证它不应该那么难......

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

(Of course, for this to work you must add SampleB to the @PrepareForTestannotation and call mockStaticfor it.)

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