JUnit testing - check for exceptions
Table of Contents
asserting that there are no exceptions
Code that is being tested:
public class Printer {
public static void printLine(final String line) {
System.out.println(line);
}
}
In case no exception is thrown and you want to explicitly illustrate this behaviour, simply add expected as in the following example:
@Test(expected = Test.None.class /* no exception expected */)
public void test_printLine() {
Printer.printLine("line");
}
asserting exceptions
JUnit 5 Jupiter assertions API introduces the assertThrows
method for asserting exceptions.
Junit5
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.
Example
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));
}
}
External references
- https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html
- https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html#assertAll(java.util.Collection)
- https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html#assertDoesNotThrow(org.junit.jupiter.api.function.Executable)
- https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html#assertThrows(java.lang.Class,org.junit.jupiter.api.function.Executable)