Test a method calling System.exit()

Today I was writing test for one of our command line tools, and I had this problem where the method dumping everything, which I really needed to be called since that’s the outcome I was checking, also called System.exit(). I had to find a way to test this anyway. I thought about using PowerMock and mocking system but that would have been complicated because I would have to find the exact class calling the System.exit(). So here is another solution to avoid the System.exit to exit (yes that’s possible I didn’t know about that either).

The secrets lays in the SecurityManager mechanism of Java, this class not only allows you to check permissions, but also to check exit event. Therefore you can throw an exception if you want to stop the exit. Here is the code:

 

protected static class ExitException extends SecurityException {
    public final int status;
    public ExitException(int status) {
        this.status = status;
    }
}

private static class NoExitSecurityManager extends SecurityManager {
    @Override
    public void checkPermission(Permission perm) {}
    @Override
    public void checkPermission(Permission perm, Object context) {} 

    @Override
    public void checkExit(int status) {
        super.checkExit(status);
        throw new ExitException(status);
    }
}

Then you can catch the exception when calling your method under test:

try {
    AdminCommandLine.main(new String[] {"-ls", folderPath});
    // You can assert false here if you really want System.exit() to be called
} catch (ExitException e) {
    // Do nothing this is expected
}

Leave a Reply