From a6253493ea558b55d0ddf3a755a5db53654ebf30 Mon Sep 17 00:00:00 2001 From: Chris Date: Wed, 28 Aug 2024 12:10:08 +0200 Subject: [PATCH] Document benefits of messageSupplier in Assertions Issue: #3153 --- .../src/docs/asciidoc/user-guide/writing-tests.adoc | 8 ++++++++ documentation/src/test/java/example/AssertionsDemo.java | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/documentation/src/docs/asciidoc/user-guide/writing-tests.adoc b/documentation/src/docs/asciidoc/user-guide/writing-tests.adoc index 49a5d4ff3f9b..9ef3c21f60b6 100644 --- a/documentation/src/docs/asciidoc/user-guide/writing-tests.adoc +++ b/documentation/src/docs/asciidoc/user-guide/writing-tests.adoc @@ -293,6 +293,14 @@ JUnit Jupiter comes with many of the assertion methods that JUnit 4 has and adds that lend themselves well to being used with Java 8 lambdas. All JUnit Jupiter assertions are `static` methods in the `{Assertions}` class. +Assertion methods can accept an optional third parameter, which can be either a `String` or a `Supplier`. +When using a `Supplier` (e.g., a lambda expression) as the message supplier, +the message is evaluated lazily. + +Lazily evaluating the assertion message can provide a performance benefit, +especially if the message construction is complex or time-consuming, +as it is only evaluated when the assertion fails. + [source,java,indent=0] ---- include::{testDir}/example/AssertionsDemo.java[tags=user_guide] diff --git a/documentation/src/test/java/example/AssertionsDemo.java b/documentation/src/test/java/example/AssertionsDemo.java index 24d8c0691769..027225ea1e2b 100644 --- a/documentation/src/test/java/example/AssertionsDemo.java +++ b/documentation/src/test/java/example/AssertionsDemo.java @@ -41,8 +41,9 @@ void standardAssertions() { assertEquals(2, calculator.add(1, 1)); assertEquals(4, calculator.multiply(2, 2), "The optional failure message is now the last parameter"); - assertTrue('a' < 'b', () -> "Assertion messages can be lazily evaluated -- " - + "to avoid constructing complex messages unnecessarily."); + + // Lazily evaluates generateFailureMessage('a','b'). + assertTrue('a' < 'b', () -> generateFailureMessage('a','b')); } @Test