Search code examples
javaunit-testingexceptionjunitjunit4

JUnit testing custom exception


I'm using JUnit and not quite sure how to test custom exception class. I have created,

public class CustomException extends Exception {

    //@param message is the exception message

    public CustomException(final String message) {
        super(message);
    }

    //@param message is the exception message
    //@param cause is the cause of the original exception

    public CustomException(final String message, final Throwable cause) {
        super(message, cause);
    }
}

main class would have many try catch such as:

catch (ParseException e) {

    throw new CustomException("Date format incorerect", e);

and I'm not sure how to write the test class for it.


Solution

  • This page should tell you everything you need to know. For the simplest case, which seems to be your case, just do this:

    @Test(expected= CustomException.class) 
    public void myTest() { 
      MyObject obj = new MyObject();
      obj.doSomethingThatMightThrowCustomException(); 
    }