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).
Use
Runtime.exec(String command)
to start JVM in a separate process.You actually can mock or stub out the
System.exit
method, in a JUnit test.For example, using JMockit you could write (there are other ways as well):
EDIT: Alternative test (using latest JMockit API) which does not allow any code to run after a call to
System.exit(n)
:Create a mock-able class that wraps System.exit()
I agree with EricSchaefer. But if you use a good mocking framework like Mockito a simple concrete class is enough, no need for an interface and two implementations.
Stopping test execution on System.exit()
Problem:
A mocked
Sytem.exit()
will not terminate execution. This is bad if you want to test thatthing2
is not executed.Solution:
You should refactor this code as suggested by martin:
And do
System.exit(status)
in the calling function. This forces you to have all yourSystem.exit()
s in one place in or nearmain()
. This is cleaner than callingSystem.exit()
deep inside your logic.Code
Wrapper:
Main:
Test: