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());
}

}

The is expecting  IllegalArgumentException to be thrown, and this is actually happening inside this lambda expression. The following screenshot shows that the test actually succeeds:

Console output of assertThrows example
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.117.214