如何在编写JUnit时绕过Runtime.getRuntime()?

unn*_*nni 7 java junit singleton unit-testing mockito

我有一个类,其中Runtime.getRuntime()用于从命令行执行脚本并获取结果以供进一步处理.

但是当我为这个类编写JUnit时,我找不到一种方法来模拟/避免这个Runtime.getRuntime().exec().

我不能使用EasyMock或PowerMock或Mockito以外的任何其他模拟API .

请给我一个克服这个问题的方法,因为这会影响代码覆盖率.

Tom*_*icz 16

你必须重构.提取Runtime.getRuntime().exec()到一个单独的类:

public class Shell {

  public Process exec(String command) {
    return Runtime.getRuntime().exec(command);
  }

}
Run Code Online (Sandbox Code Playgroud)

现在,在调试时,以某种方式调用getRuntime()显式注入Shell类:

public class Foo {

  private final Shell shell;

  public Foo(Shell shell) {
    this.shell = shell;
  }

  //...
  shell.exec(...)

}
Run Code Online (Sandbox Code Playgroud)

在JUnit测试中,只需Shell通过将它传递给构造函数来注入mock 类:

@Mock
private Shell shellMock;

new Foo(shellMock);
Run Code Online (Sandbox Code Playgroud)

旁注:是的,我没有创建Shell一个实现的接口.你介意吗?Mockito不是.额外奖励:您现在可以验证是否调用了正确的流程:

verify(shellMock).exec("/usr/bin/gimp");
Run Code Online (Sandbox Code Playgroud)