How to get the value that is passed to Runtime.getRuntime.exit(value) in a JUnit test case

邮差的信 提交于 2019-12-11 08:13:10

问题


I have to write a Test case in JUnit for a Class lets call it C1 which internally calls Runtime.getRuntime.exit(somevalue).

The class C1 has a main method which accepts some arguments and the creates a CommandLine and then depending on the passed arguments does the specific tasks.

Now all tasks after executing call a Runtime.getRuntime.exit(somevalue). The somevalue defines whether the task was executed successfully (means somevalue is 0) or had errors (means somevalue is 1).

In the JUnit test case of this I have to get this somevalue and check whether it is the desired somevalue or not.

How do I get the somevalue in the JUnit test case.


回答1:


You can override security manager to catch the exit code, if you use a mocking framework it would be more concise:

@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);
}


来源:https://stackoverflow.com/questions/11505109/how-to-get-the-value-that-is-passed-to-runtime-getruntime-exitvalue-in-a-junit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!