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.
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.
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.
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With