此方法无法通过单元测试进行测试,而只能通过集成测试进行测试。要进行单元测试,您可以进行一个小的重构。引入一个新接口ProcessBuilderFactory
(和一个默认实现)并将其注入您的类。
public interface ProcessBuilderFactory {
ProcessBuilder createProcessBuilder(String command);
}
public class DefaultProcessBuilderFactory implements ProcessBuilderFactory {
public ProcessBuilder createProcessBuilder(String command) {
return new ProcessBuilder(command);
}
}
public class ProcessExecutor {
private ProcessBuilderFactory processBuilderFactory;
private ProcessExecutor(ProcessBuilderFactory processBuilderFactory) {
this.processBuilderFactory = processBuilderFactory;
}
public void execute(String command) {
ProcessBuilder processBuilder = processBuilderFactory.createProcessBuilder(command);
Process process = processBuilder.start();
int exitValue = process.waitFor();
if (exitValue != 0) {
throw new RuntimeException("a message here...");
}
}
}
然后你可以通过注入一个 mock来进行单元ProcessBuilderFactory
测试。您开始编写测试,创建一个 mock ProcessBuilderFactory
,返回一个 mock ProcessBuilder
...该死的,ProcessBuilder
太final
:(
强烈提醒:先写测试!
所以我们有两个选择:
- 引入一个新的接口来包装
ProcessBuilder
一个默认实现......以同样的方式我们创建ProcessBuilderFactory
- 撤消重构并查看PowerMock,以进行最终类模拟