Building Cloud Expertise with centron - Our Tutorials

Whether you are a beginner or an experienced professional, our practical tutorials provide you with the knowledge you need to make the most of our cloud services.

Testing Expected Exceptions in JUnit

We can test expected exceptions using JUnit 5 assertThrows assertion. This JUnit assertion method returns the thrown exception, so we can use it to assert exception message too.

JUnit Assert Exception

Here is a simple example showing how to assert exception in JUnit 5.

String str = null;
assertThrows(NullPointerException.class, () -> str.length());

JUnit 5 Assert Exception Message

Let’s say we have a class defined as:

class Foo {
    void foo() throws Exception {
        throw new Exception("Exception Message");

Let’s see how we can test exception as well as its message.

Foo foo = new Foo();
Exception exception = assertThrows(Exception.class, () ->;
assertEquals("Exception Message", exception.getMessage());

JUnit 4 Expected Exception

We can use JUnit 4 @Test annotation expected attribute to define the expected exception thrown by the test method.

@Test(expected = Exception.class)
public void test() throws Exception {
    Foo foo = new Foo();;

JUnit 4 Assert Exception Message

If we want to test exception message, then we will have to use ExpectedException rule. Below is a complete example showing how to test exception as well as exception message.

package com.journaldev.junit4;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class JUnit4TestException {

    public ExpectedException thrown = ExpectedException.none();

    public void test1() throws Exception {
        Foo foo = new Foo();
        thrown.expectMessage("Exception Message");;

That’s all for a quick roundup on testing expected exceptions in JUnit 5 and JUnit 4.

Start Your Cloud Journey Today with Our Free Trial!

Dive into the world of cloud computing with our exclusive free trial offer. Experience the power, flexibility, and scalability of our cloud solutions firsthand.

Try for free!