I've got a few methods that should call System.exit()
on certain inputs. Unfortunately, testing these cases causes JUnit to terminate! Putting the method calls in a new Thread doesn't seem to help, since System.exit()
terminates the JVM, not just the current thread. Are there any common patterns for dealing with this? For example, can I subsitute a stub for System.exit()
?
[EDIT] The class in question is actually a command-line tool which I'm attempting to test inside JUnit. Maybe JUnit is simply not the right tool for the job? Suggestions for complementary regression testing tools are welcome (preferably something that integrates well with JUnit and EclEmma).
A quick look at the api, shows that System.exit can throw an exception esp. if a securitymanager forbids the shutdown of the vm. Maybe a solution would be to install such a manager.
For VonC's answer to run on JUnit 4, I've modified the code as follows
There are environments where the returned exit code is used by the calling program (such as ERRORLEVEL in MS Batch). We have tests around the main methods that do this in our code, and our approach has been to use a similar SecurityManager override as used in other tests here.
Last night I put together a small JAR using Junit @Rule annotations to hide the security manager code, as well as add expectations based on the expected return code. http://code.google.com/p/junitsystemrules/
You can test System.exit(..) with replacing Runtime instance. E.g. with TestNG + Mockito:
Calling System.exit() is a bad practice, unless it's done inside a main(). These methods should be throwing an exception which, ultimately, is caught by your main(), who then calls System.exit with the appropriate code.
Indeed, Derkeiler.com suggests:
System.exit()
?System.exit()
to actually exit the JVM:Update December 2012:
Will proposes in the comments using System Rules, a collection of JUnit(4.9+) rules for testing code which uses
java.lang.System
.This was initially mentioned by Stefan Birkner in his answer in December 2011.
For instance: