Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit testing custom exception [duplicate]

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.

like image 480
Hash Avatar asked Oct 23 '13 05:10

Hash


People also ask

How do you repeat a JUnit test?

JUnit Jupiter @RepeatedTest annotation is used to repeat the test case for specified no. of times. Each invocation of the test case behaves like a regular @Test method, so it has support for the same lifecycle callbacks and extensions in JUnit 5.

How do you throw a custom exception in Java JUnit?

1. Test Exception in JUnit 5 - using assertThrows() method. You put the code that can throw exception in the execute() method of an Executable type - Executable is a functional interface defined by JUnit. The message is optional, to be included in the error message printed when the test fails.

How do you throw a custom exception in JUnit 5?

In JUnit 5, to write the test code that is expected to throw an exception, we should use Assertions. assertThrows(). In the given test, the test code is expected to throw an exception of type ApplicationException or its subtype. Note that in JUnit 4, we needed to use @Test(expected = NullPointerException.


1 Answers

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(); 
} 
like image 145
Vidya Avatar answered Oct 11 '22 05:10

Vidya