java 在一个类中使用 Mockito 间谍从另一个类调用静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43196314/
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-03 07:10:49  来源:igfitidea点击:

Using Mockito spy in one class to Call static method from another class

javajunitmockingmockito

提问by R.C

Trying to use Mockito's spy function for my JUnit test. I originally had a Class:

试图在我的 JUnit 测试中使用 Mockito 的 spy 函数。我最初有一个班级:

public class App1 { 
    public String method1() {
        sayHello();
    }

    public sayHello() {
        Systems.out.println("Hello");
    }
}

Everything in my test class was working correctly with mockito spy on above class:

我的测试课程中的所有内容都与上面课程的模拟间谍一起正常工作:

@Test(expected = IOException.class)
public void testMethod1Failure(){   
    App1 a1 = spy(App1);
    doThrow(IOException.class).when(a1).sayHello();

    a1.method1();
}

But after that i had to switch things around and take sayHello() method into another class to be used as static method:

但在那之后我不得不改变事情并将 sayHello() 方法带入另一个类以用作静态方法:

public class App1 { 
    public String method1() {
        App2.sayHello();
    }
}

public class App2 { 
    public static void sayHello() {
        Systems.out.println("Hello");
    }
}

After this change, my original JUnit testcase is broken and i am unsure how i can use Mockito spy to start App1 that calls the external App2 static method... does anyone know how i can do it? Thanks in advance

在此更改之后,我原来的 JUnit 测试用例被破坏了,我不确定如何使用 Mockito spy 来启动调用外部 App2 静态方法的 App1……有谁知道我该怎么做?提前致谢

回答by VinPro

Mockito does not support mocking static code. Here are some ways to handle it:

Mockito 不支持模拟静态代码。以下是一些处理方法:

  • Use PowerMockito or similar framework as suggested here: Mocking static methods with Mockito.
  • Refactor your code converting static method back to an instance method. As you've found static methods are not easy to Unit test.
  • If it's inexpensive to execute actual static method in question then just call it.
  • 按照此处的建议使用 PowerMockito 或类似框架:使用 Mockito 模拟静态方法
  • 重构将静态方法转换回实例方法的代码。正如您发现静态方法不容易进行单元测试。
  • 如果执行有问题的实际静态方法成本低廉,则只需调用它。