JUnit 5 Lazy Assertion Message Tutorial

JUnit is a popular unit testing framework for Java. In JUnit 5, assertions are used to check the expected outcome of a test case. Assertion messages are used to provide more information about the failed test and help in debugging.

The Lazy Assertion Message feature in JUnit 5 allows you to specify the assertion message only when the assertion fails. This can be useful when the message is expensive to compute or when it contains a lot of information that is not necessary unless the assertion fails.

To use Lazy Assertion Message in JUnit 5, you need to use the assertEquals method and pass a lambda expression as the last argument. This lambda expression should return the message that you want to display when the assertion fails.

Example 1

assertEquals(expected, actual, () -> "Expected " + expected + " but got " + actual);

In the above example, the message “Expected ” + expected + ” but got ” + actual” will be computed only if the assertion fails. Otherwise, it will not be executed.

You can also use the assertTrue and assertFalse methods in a similar way to specify a lazy assertion message. Here is an example:

assertTrue(condition, () -> "Expected condition to be true but it was false");

A Lazy Assertion Message can be useful when you have a long or complex message that you only want to compute if the assertion fails. It can help improve the performance of your test cases by avoiding unnecessary computation of the message.

Example 2

The below code snippet is an example of a JUnit test that imports import parameters from a CSV file. It tests the integer subtraction, and if the result is incorrect fails. Notice how it uses the Lazy Assertion Message in the assertEquals() assertion.

@CsvFileSource(resources = "/integerSubtraction.csv")
void integerSubtraction(int minuend, int subtrahend, int expectedResult) {
    System.out.println("Running Test "+minuend+" - " +subtrahend+ " = " + expectedResult);

    int actualResult = calculator.integerSubtraction(minuend, subtrahend);

    assertEquals(expectedResult, actualResult,
            ()->minuend + "-" + subtrahend + " did not produce " + expectedResult);

Video Tutorial

I hope this tutorial has helped you understand how to use Lazy Assertion Message in JUnit 5. If you have any questions, please feel free to ask.

To learn more, check out JUnit 5 tutorials.

Happy learning!