Code Snippet

Just another Code Snippet site

[Java] Test exit status

class ExitSecurityManager extends SecurityManager {
    List<Integer> allowedExitCodes;

    public Exit0SecurityManager(Integer... allowedExitCodes) {
        this.allowedExitCodes = Arrays.asList(allowedExitCodes);
    }

    @Override
    public void checkExit(final int status) {
        if (allowedExitCodes.contains(status)) {
            throw new NoException();
        } else {
            throw new SecurityException("Wrong exit status : " + status);
        }
    }

    @Override
    public void checkPermission(final Permission perm) {}

    @Override
    public void checkPermission(final Permission perm, final Object context) {}

    public class NoException extends RuntimeException {
    }
}
    @Test
    public void testExitStatus() {
        ArrayList<String> args = new ArrayList<String>();
        String[] tab = new String[args.size()];
        tab = args.toArray(tab);

        SecurityManager currentManager = System.getSecurityManager();
        System.setSecurityManager(new ExitSecurityManager(0));
        try {
            MyClass.main(tab);
        } catch (NoException ex) {
            Assert.assertTrue(true); // No exception raised
        } catch (Exception e) {
            Assert.fail("Unexpected exception raised : " + e.getMessage());
        } finally {
            System.setSecurityManager(currentManager);
        }
    }


Comments are currently closed.