Re: JUnit + System.exit(-1): Looking for alternatives
Koos Pol <koos@geen.spam> writes:
....
Due to the many
possible failure points I created a general ErrorHandler class which dumps
to log4j and then quits via System.exit(-1).
1. Does anyone know of a way to make JUnit not barf on the System.exit(-1)?
Try modifying the TestCase to run with a security manager that
prevents calling System.exit, then catch the SecurityException.
Something like (untested!):
----
public class SecurityTestCase extends TestCase {
private class ExitException extends SecurityException {
public final int exitCode;
public ExitException(int code) {
super("There is no escape!");
this.exitCode = code;
}
}
private class NoExitSecurityManager extends SecurityManager {
public checkExit(int status) {
super.checkExit(); // first call on preventing.
throw new ExitException(status);
}
};
public void setUp() throws Exception {
System.setSecurityManager(new NoExitSecurityManager());
}
public void tearDown() throws Exception {
System.setSecurityManager(null);
}
}
---
and then make a test like:
public void testExit() throws Exception {
try {
somethingThatExits();
fail("System.exit() expected");
} catch (ExitException e) {
assertEquals("Exit code", 42, e.exitCode);
}
}
Or perhaps you can create a policy file that revokes the permission
to exit from your own packages.
See http://java.sun.com/j2se/1.5.0/docs/guide/security/PolicyFiles.html
2. Is there a way to gracefully abort besides System.exit(), (which is far
from gracefully)?
As already said, a custom unchecked exception causes no syntactic
overhead and won't be caught (unless you catch RuntimeException or
Exception directly somewhere else, which you really, really shouldn't,
for pretty much that reason), and won't be lost unless you have
a finally-block that ends abruptly (which you shouldn't really do either).
Dying gracefully will also allow finally blocks to release acquired
resources where necessary.
/L
--
Lasse Reichstein Nielsen - lrn@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'