Exception testing in JUnit4

In JUnit4 we could just specify the expected exception as a parameter of the @Test annotation.

    @Test(expected = ArithmeticException.class)
    public void divisionByZeroThrowsArithmeticExceptionTest() {
        int x = 1 / 0;
    }

Exception testing in JUnit5

Now in JUnit5 we cannot use @Test for that.

Instead we can write assertions more “functional” way.

    @Test
    public void divisionByZeroThrowsArithmeticExceptionTest() {
        Assertions.assertThrows(ArithmeticException.class, () -> {
            int x = 1 / 0;
        });
    }

Another JUnit5 exception testing example

    @Test
    public void invalidEmailShouldCauseBadRequestTest() {
        ...
        Assertions.assertThrows(BadRequestException.class, () -> {
            client.updateEmail("new invalid email @mymaildomain.com", username, password);
        });
    }