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 substitute a stub for System.exit()?
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).
Indeed, Derkeiler.com suggests:
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:
2023: Emmanuel Bourg reports in the comments: