Open In App

JUnit 5 – Expected Exception

In JUnit 5, Exception handling is changed compared to exception handling in JUnit 4. JUnit 5 provides the assertThrows() method for that particular exception thrown during execution of the Testing of an application. This assertThrows is available in org.junit.jupiter.api.Assertions class. Mostly this assertThrows() is used for testing expected exceptions.

Prerequisites

  • Basic knowledge on exception handling
  • Basic knowledge on testing
  • Basic knowledge on JUnit 5 testing framework
  • Must know information about Annotations in JUnit 5

Syntax of JUnit 5 Expected Exception

static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable)

Parameters:

Returns:

The exception was thrown during the execution of a given block of code in the class.



Example of JUnit 5 – Expected Exception

Now we will execute this by using a basic example for a better understanding of the concept. Now we will take one Java class that is MyClass, and after that we will take one more Java class for Testing which is MyClassTest.

MyClass.java:




public class MyClass {
  
    public void throwException() throws MyException {
        throw new MyException("This is Custom exception message");
    }
}

In this above code, we have created one method that is throwException() which is throws an exception type MyException. In that method we have given test message as This is Custom exception message.



MyClassTest.java:

Now we will implement the testing class. The class name is MyClassTest which is used for testing the exceptions of MyClass.




import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
  
public class ExampleTest {
  
    @Test
    public void testException() {
        MyClass myClass = new MyClass();
        MyException exception = assertThrows(MyException.class, () -> {
            myClass.throwException();
        });
  
        assertEquals("This is Custom exception message", exception.getMessage());
    }
}

In above example we have created object for MyClass after that we have uses assertThrows() method for checking excepted exception is came or not. And the assertEquals() is check the exception is equals with given exception and result exception. If both are same, then the test case will get passed otherwise it will not get passed.

Advantages of Expected Exception in JUnit 5

Conclusion

The Junit 5 provides assertThrows() method for checking excepted exception in testing. And it contributes to writing robust and reliable tests for our code in testing. And it is most powerful tool in JUnit 5 for testing expected exceptions and it allows us to assert that a specific type of exception is thrown during the execution of a particular code block of application.


Article Tags :