0

Duplicate: Java: How to test methods that call System.exit()?


I am having a bit of trouble designing a unit test for a method that exits the application by calling system.exit(). Actually, this is the constructor of a class which tests some conditions and decides to exit the application. So it is this particular eventuality that I'd like to test.

Is there a particular assert that I could use, or any other suggestions?

public MyClass(arg1, arg2, arg3){
    if(argsTestingIsOK){
        continue;       
    }else{
        System.exit(0);
    }
}
Community
  • 1
  • 1
denchr
  • 4,142
  • 13
  • 48
  • 51

2 Answers2

7

Instead of exit()-ing in the constructor, throw an IllegalArgumentException instead (since that's what's really happening) and leave it to the caller to handle the exception. The application code can be written to process the exception while the JUnit test can assert that the exception occurs.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike Reedell
  • 1,567
  • 15
  • 23
4

Don't do this in a constructor. It's a bad idea, and it's misleading to anyone using your code.

The best practice is to only use something like System.exit() in a main method or in the entry point to your application - definitely not in the middle of object construction code.

matt b
  • 138,234
  • 66
  • 282
  • 345