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

1

1

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.

Sudbury answered 16/7, 2012 at 13:14 Comment(2)
Are you using a mocking framework?Obelia
Simple JUnit Test Case classes.Sudbury
O
3

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);
}
Obelia answered 16/7, 2012 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.