我有一个类,其中 Runtime.getRuntime() 用于从命令行执行脚本并获取结果以进行进一步处理。
但是当我为这个类编写 JUnit 时,我找不到一种方法来模拟/避免这个 Runtime.getRuntime().exec() 。
我不能使用 EasyMock 或 PowerMock 或除 Mockito 之外的任何其他模拟 api。
请给我一个克服这个问题的方法,因为这会影响代码覆盖率。
最佳答案
你必须重构。将 Runtime.getRuntime().exec()
提取到一个单独的类中:
public class Shell {
public Process exec(String command) {
return Runtime.getRuntime().exec(command);
}
}
现在不再调用 getRuntime()
显式地将 Shell
类以某种方式注入(inject)到您正在测试的类中:
public class Foo {
private final Shell shell;
public Foo(Shell shell) {
this.shell = shell;
}
//...
shell.exec(...)
}
在 JUnit 测试中,通过将模拟的 Shell
类传递给构造函数来简单地注入(inject)它:
@Mock
private Shell shellMock;
new Foo(shellMock);
旁注:是的,我不是用一个实现创建一个Shell
接口(interface)。你介意吗? Mockito 不是。奖励:您现在可以验证是否调用了正确的进程:
verify(shellMock).exec("/usr/bin/gimp");
关于java - 编写 JUnit 时如何绕过 Runtime.getRuntime()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10846595/