How to assert Exceptions in JUnit

JUnit 5 provides several ways to assert that a certain exception is thrown in a @Test method. In this tutorial, we will show you how to use assert Exceptions using JUnit5 and JUnit4 Tests.

In order to assert that your JUnit 5 Test throws an Exception, you can rely on the following assertions:

  • The assertThrows() method of the Assertions class
  • The assertAll() method of the Assertions class with the assertThrows() method

Let’s see with a complete examples all options.

Setting up our Test

Firstly, let’s define a simple Java Class which can potentially throw some Exceptions:

public class Calculator {
    public int divide(int dividend, int divisor) {
        if (divisor == 0) {
            throw new IllegalArgumentException("Divisor cannot be zero");
        }
        return dividend / divisor;
    }

    public int square(int number) {
        if (number < 0) {
            throw new IllegalArgumentException("Number cannot be negative");
        }
        return number * number;
    }
}

Next, let’s add the following Test Class to assert Exception on Tests:

class CalculatorTest {
    private final Calculator calculator = new Calculator();

    @Test
    void testDivideByZero() {
        assertThrows(IllegalArgumentException.class,
                () -> calculator.divide(1, 0));
    }

    @Test
    void testSquareWithNegativeNumber() {
        assertThrows(IllegalArgumentException.class,
                () -> calculator.square(-1));
    }

    @Test
    void testBothMethods() {
        assertAll("exception tests",
                () -> assertThrows(IllegalArgumentException.class,
                        () -> calculator.divide(1, 0)),
                () -> assertThrows(IllegalArgumentException.class,
                        () -> calculator.square(-1))
        );
    }
}

The assertAll() method of the Assertions class allows you to group multiple assertion invocations and to report all failures in one go.
This can be useful when you want to test multiple exception scenarios in one test method.

The assertThrows() method works well in conjunction with other assertion methods to perform additional checks on the exception object, such as asserting the exception message or the cause.

It’s important to note that regardless of the method you choose, JUnit will only consider the test as successful if the exception specified is thrown and if it’s not thrown the test will fail.

Run the JUnit Test from the IDE from the command line and verify that all assertions are ok:

How to assert a JUnit 5 exception

JUnit 4 Expected Exceptions

If you are using JUnit4 to assert Exceptions, then you have to use the expected attribute of the JUnit 4 @Test annotation. For example:

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

Conclusion

In this article we have discussed how to assert Exceptions using JUnit Jupiter and JUnit 4 framework with a simple Test example

Source code: https://github.com/fmarchioni/mastertheboss/tree/master/test/junit5-assert-exception

Found the article helpful? if so please follow us on Socials