【问题标题】:How to get the value that is passed to Runtime.getRuntime.exit(value) in a JUnit test case如何在 JUnit 测试用例中获取传递给 Runtime.getRuntime.exit(value) 的值
【发布时间】:2012-07-16 13:14:00
【问题描述】:

我必须在JUnit 中为Class 编写一个测试用例,我们称之为C1,它在内部调用Runtime.getRuntime.exit(somevalue)

C1 类有一个main 方法,它接受一些arguments 并创建一个CommandLine,然后根据传递的arguments 执行特定任务。

现在执行后的所有任务都调用Runtime.getRuntime.exit(somevalue)somevalue 定义任务是成功执行(表示某个值为 0)还是有错误(表示某个值为 1)。

在这个 JUnit 测试用例中,我必须得到这个 somevalue 并检查它是否是所需的 somevalue

如何在 JUnit 测试用例中获取 somevalue

【问题讨论】:

  • 你在使用模拟框架吗?
  • 简单的 JUnit 测试用例类。

标签: java junit runtime runtime.exec


【解决方案1】:

您可以覆盖安全管理器来捕获退出代码,如果您使用模拟框架会更简洁:

@Test
public void when_main_is_called_exit_code_should_be_1() throws Exception {
    final int[] exitCode = new int[1];
    System.setSecurityManager(new SecurityManager() {
        @Override
        public void checkExit(int status) {
            exitCode[0] = status;
            throw new RuntimeException();
        }});

    try { main(); } catch(Exception e) {}

    assertEquals(exitCode[0], 1);
}

public static void main() {
    System.exit(1);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-14
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多