1 package org.djutils.cli; 2 3 import java.security.Permission; 4 5 /** 6 * ExitHelper assists in testing System.exit() calls. Normally System.exit() calls cannot be tested by Maven SureFire, see 7 * <a href= "https://maven.apache.org/surefire/maven-surefire-plugin/faq.html#vm-termination"> 8 * https://maven.apache.org/surefire/maven-surefire-plugin/faq.html#vm-termination</a><br> 9 * Based on <a href="https://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit"> 10 * https://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit</a><br> 11 * Other solutions can be found at 12 * <a href="https://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit"> 13 * https://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit</a><br> 14 * <p> 15 * Copyright (c) 2019-2021 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br> 16 * BSD-style license. See <a href="https://djunits.org/docs/license.html">DJUNITS License</a>. 17 * <p> 18 * @author <a href="https://www.tudelft.nl/averbraeck" target="_blank">Alexander Verbraeck</a> 19 */ 20 public class ExitHelper 21 { 22 /** Exception that will be thrown instead of the System.exit() call. */ 23 public static class ExitException extends SecurityException 24 { 25 /** */ 26 private static final long serialVersionUID = 1L; 27 28 /** the exit code. */ 29 @SuppressWarnings("checkstyle:visibilitymodifier") 30 public final int status; 31 32 /** 33 * Instantiate the exception. 34 * @param status the exit code 35 */ 36 public ExitException(final int status) 37 { 38 super("System.exit(" + status + ") called"); 39 this.status = status; 40 } 41 } 42 43 /** The security manager for the exit exception. */ 44 public static class NoExitSecurityManager extends SecurityManager 45 { 46 @Override 47 public void checkPermission(final Permission perm) 48 { 49 // allow anything. 50 } 51 52 @Override 53 public void checkPermission(final Permission perm, final Object context) 54 { 55 // allow anything. 56 } 57 58 /** {@inheritDoc} */ 59 @Override 60 public void checkExit(final int status) 61 { 62 super.checkExit(status); 63 throw new ExitException(status); 64 } 65 } 66 }