1

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.

Roy Sht
  • 113
  • 1
  • 1
  • 8

2 Answers2

4

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 ?

AdrianM
  • 175
  • 7
  • 1
    You're right, thank you. This is indeed much more elegant. – Roy Sht May 29 '19 at 18:47
  • If it's about communicating with the OS, i.e., for use in scripts, an exception doesn't do you any good. The standard way is exit codes, and in such cases it's IMHO fine to test that the right codes are returned. The exit codes are part of the published interface. – Robert May 29 '19 at 18:53
1

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.

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81