java - 使用 PowerMockito 模拟 java.lang.Runtime

标签 java junit mockito powermock

想为类似这样的方法编写单元测试

public static void startProgram() {
    process = Runtime.getRuntime().exec(command, null, file);
}

出于某些原因我不想注入(inject)运行时对象,所以我想 stub 它返回运行时模拟的 getRuntime 方法...我这样试过:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Runtime.class)
public class ProgramTest {

    @Test
    public void testStartProgram() {
        Runtime mockedRuntime = PowerMockito.mock(Runtime.class);

        PowerMockito.mockStatic(Runtime.class);
        Mockito.when(Runtime.getRuntime()).thenReturn(mockedRuntime);

        ... //test
    }
}

但这行不通。实际上似乎没有什么是可以 mock 的。在测试中,使用了正常的运行时对象。

有人知道为什么这不起作用和/或它是如何工作的吗?

由于这个迷你示例似乎无法重现问题,因此这里是完整的测试代码: 测试方法(缩短)

public static synchronized long startProgram(String workspace) {
    // Here happens someting with Settings which is mocked properly
    File file = new File(workspace);
    try {
        process = Runtime.getRuntime().exec(command, null, file);
    } catch (IOException e) {
        throw e;
    }
    return 0L;
}

和测试:

@Test
public void testStartProgram() {
    PowerMockito.mockStatic(Settings.class);
    Mockito.when(Settings.get("timeout")).thenReturn("42");

    Runtime mockedRuntime = Mockito.mock(Runtime.class);
    // Runtime mockedRuntime = PowerMockito.mock(Runtime.class); - no difference
    Process mockedProcess = Mockito.mock(Process.class);

    Mockito.when(mockedRuntime.exec(Mockito.any(String[].class), Mockito.any(String[].class),
                    Mockito.any(File.class))).thenReturn(mockedProcess);

    PowerMockito.mockStatic(Runtime.class);
    Mockito.when(Runtime.getRuntime()).thenReturn(mockedRuntime);

    startProgram("doesnt matter");
}

然后,在测试中,对 Runtime.getRuntime() 的调用不会带来模拟,这就是抛出 IOException 的原因,因为 String 不是目录...

最佳答案

我在评论中的错误,道歉,我有一个测试的内部类,这就是为什么我没有遇到麻烦。然后我意识到这一点并看到你的 @PrepareForTest(Runtime.class) 应该读作 @PrepareForTest(MyClass.class) (用你有的任何名称替换 MyClass)因为 Runtime 是一个系统类。您可以阅读更多相关信息 here并查找更多示例 here .

关于java - 使用 PowerMockito 模拟 java.lang.Runtime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24039184/

相关文章:

java - 如何模拟java类中的特定静态方法?

Java 程序具有 Linux 方法 - 我可以在其上运行 Junit 测试用例吗?

java - 测试方法 - Ruby/RSpec 与 Java/Mockito

java - 无法在 Spring Boot 测试中加载类 [pg-uuid]

java - 了解 Mockito 验证背后的语义

java - java中的多线程

java.util.Set 添加和删除方法签名区别

java - 使用 "real data"设置测试系统

Java 代理示例正在创建堆栈溢出?

Java:使用迭代器测试方法