views:

139

answers:

2

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


Hello,

I am having a bit of a 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 eventuallity that I'd like to test.

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

Many thanks in advance

public MyClass(arg1, arg2, arg3){
    if(argsTestingIsOK){
        continue;    
    }else{
        System.exit(0);
    }
}
+3  A: 

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
+6  A: 

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 the exception occurs.

Mike Reedell
thanks Mike, that's a great suggestion actually! Will try that now!
denchr