0

我的方法中有一个内部依赖项:

String myString ... //do some stuff to string determined my method parameters
Process p = Runtime.getRuntime().exec(myString);

myString 是本地方法范围,并且不会返回 - 无论如何可以通过单元测试来测试 myString 的样子?除了将其作为外部依赖注入并创建字符串的模拟之外。

4

2 回答 2

2

我会在合作者中提取 exec 部分,并模拟这个合作者:

public interface ProgramLauncher {
    Process exec(String command);
}

...

@Test
public void test() {
    ProgramLauncher mockLauncher = mock(ProgramLauncher.class);
    YourClass underTest = new YourClass(mockLauncher);
    underTest.callMethod();
    verify(mockLauncher).exec("the expected command");
}
于 2013-08-02T08:22:35.697 回答
1

我宁愿提取

//做一些事情来确定我的方法参数

分离方法并仅测试此方法。

于 2013-08-02T08:27:13.230 回答