O'Reilly logo

Mastering Software Testing with JUnit 5 by Boni García

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Asserting exceptions

Another important Jupiter assertion is assertThrows. This assertion allows to verify if a given exception is raised in a piece of code. To that aim, the method assertThrows accepts two arguments. First, the exception class expected, and second, an executable object (lambda expression), in which the exception is supposed to happen:

package io.github.bonigarcia;import static org.junit.jupiter.api.Assertions.assertEquals;import static org.junit.jupiter.api.Assertions.assertThrows;import org.junit.jupiter.api.Test;class ExceptionTest {    @Test    void exceptionTesting() {          Throwable exception =             assertThrows(IllegalArgumentException.class,            () -> {               throw new IllegalArgumentException("a message");});          assertEquals("a message", exception.getMessage()); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required