11

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.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Hash
  • 7,726
  • 9
  • 34
  • 53
  • To know how to test something you need a specification of what that thing *ought* to do. You have not provided such a specification, so this question is impossible to answer. – Raedwald Dec 18 '15 at 19:52

2 Answers2

16

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(); 
} 
Vidya
  • 29,932
  • 7
  • 42
  • 70
0

I hope this can help you.

public class YourTestClass
{
    @Test
    public void yourTestMethodName() throws CustomeException {
        //your logic goes here.
        if (condition) {
           throw new CustomeException(<Message to display while throwing an error>);
        }
    }
}

Also you can try the following site http://junit.sourceforge.net/javadoc/org/junit/Test.html

Morgoth
  • 4,935
  • 8
  • 40
  • 66
Ashok kumar
  • 435
  • 4
  • 13