From 3646b7d37e3401d9cda0106290bbf9cb36a735b2 Mon Sep 17 00:00:00 2001 From: Chris C Date: Tue, 17 Sep 2024 17:02:09 +0200 Subject: [PATCH] Document benefits of `messageSupplier` in `Assertions` (#3938) Resolves #3153. (cherry picked from commit 3b85a030a7a0ecb328eef89c993feb3b81256e43) --- .../src/docs/asciidoc/user-guide/writing-tests.adoc | 7 +++++++ documentation/src/test/java/example/AssertionsDemo.java | 9 +++++++-- 2 files changed, 14 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 3a161bf3185f..463faad468c8 100644 --- a/documentation/src/docs/asciidoc/user-guide/writing-tests.adoc +++ b/documentation/src/docs/asciidoc/user-guide/writing-tests.adoc @@ -293,6 +293,13 @@ 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 optionally accept the assertion message as their third parameter, which +can be either a `String` or a `Supplier`. + +When using a `Supplier` (e.g., a lambda expression), the message is evaluated +lazily. This can provide a performance benefit, especially if 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..c1b1c47873d9 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 @@ -160,6 +161,10 @@ private static String greeting() { return "Hello, World!"; } + private static String generateFailureMessage(char a, char b) { + return "Assertion messages can be lazily evaluated -- " + + "to avoid constructing complex messages unnecessarily." + (a < b); + } } // end::user_guide[] // @formatter:on