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.

JHS
  • 7,761
  • 2
  • 29
  • 53

1 Answers1

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);
}
Garrett Hall
  • 29,524
  • 10
  • 61
  • 76