JUnit testing - check for exceptions

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

https://github.com/explorer436/programming-playground/tree/main/java-playground/my-java-solutions/src/test/java/com/my/company/checkingexceptions

JUnit 5 Jupiter assertions API introduces the assertThrows method for asserting exceptions.

Junit5

https://blogs.oracle.com/javamagazine/post/migrating-from-junit-4-to-junit-5-important-differences-and-benefits

JUnit 5 (Jupiter) provides three functions to check exception absence/presence:

  1. assertAll​()

    Asserts that all supplied executables do not throw exceptions.

  2. 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).

  3. 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

  1. https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html
  2. https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html#assertAll(java.util.Collection)
  3. https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/Assertions.html#assertDoesNotThrow(org.junit.jupiter.api.function.Executable)
  4. 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)

Links to this note