JUnit 5 (Jupiter) provides three functions to check exception absence/presence:
assertAll?()
Asserts that all supplied executables
do not throw exceptions.
assertDoesNotThrow?()
Asserts that execution of the
supplied executable
/supplier
does not throw any kind of exception.
This function is available
since JUnit 5.2.0 (29 April 2018).
assertThrows?()
Asserts that execution of the supplied executable
throws an exception of the expectedType
and returns the exception.
package test.mycompany.myapp.mymodule;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class MyClassTest {
@Test
void when_string_has_been_constructed_then_myFunction_does_not_throw() {
String myString = "this string has been constructed";
assertAll(() -> MyClass.myFunction(myString));
}
@Test
void when_string_has_been_constructed_then_myFunction_does_not_throw__junit_v520() {
String myString = "this string has been constructed";
assertDoesNotThrow(() -> MyClass.myFunction(myString));
}
@Test
void when_string_is_null_then_myFunction_throws_IllegalArgumentException() {
String myString = null;
assertThrows(
IllegalArgumentException.class,
() -> MyClass.myFunction(myString));
}
}