Reputation: 123
I am trying to test a file processing program with Junit. In some cases, the program should print an error and finish its run. However, using "System.exit(-1)" causes the program to exit the entire Junit tests. Is there some way of avoiding it?
I can instead print the error and then return null
, however I find it quite inelegant.
private List<String> parseData(String[] args){
if (args.length != 2){
System.err.println(ERROR + INPUT_ERROR + "\n");
System.exit(EXIT_CODE);
Is there a way to check if the program called "System.exit" without closing it? Thank you.
Upvotes: 2
Views: 654
Reputation: 37950
While I think AdrianM's solution is the ideal one, you could also solve this with mocking.
Option one: Use a mocking framework such as PowerMock that lets you mock static methods so that you can make System.exit
do nothing.
Option two: Use dependency injection and any mocking framework. Create this interface and implementing class:
public interface SystemExit {
void exit(int code);
}
public class SystemExitImpl implements SystemExit {
public void exit(int code) {
System.exit(code);
}
}
Then, make the class that contains parseData
take a SystemExit
as a constructor parameter and store it in a member variable (or have a setter for the member variable that lets you set it after construction). In your production code, pass a SystemExitImpl
. In your test, create a mock for SystemExit
and pass that instead.
Upvotes: 1
Reputation: 175
I think it's more inelegant to use System.exit to validate input parameters. Why not just throw an exception and let the caller of this method handle it ?
Upvotes: 4