Skip to content

Commit 1069d5e

Browse files
Document benefits of messageSupplier in Assertions
Issue: #3153
1 parent d85dd9b commit 1069d5e

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

documentation/src/docs/asciidoc/user-guide/writing-tests.adoc

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,14 @@ JUnit Jupiter comes with many of the assertion methods that JUnit 4 has and adds
293293
that lend themselves well to being used with Java 8 lambdas. All JUnit Jupiter assertions
294294
are `static` methods in the `{Assertions}` class.
295295

296+
Assertion methods can accept an optional third parameter, which can be either a `String` or a `Supplier<String>`.
297+
When using a `Supplier<String>` (e.g., a lambda expression) as the message supplier,
298+
the message is evaluated lazily.
299+
300+
Lazily evaluating the assertion message can provide a performance benefit,
301+
especially if the message construction is complex or time-consuming,
302+
as it is only evaluated when the assertion fails.
303+
296304
[source,java,indent=0]
297305
----
298306
include::{testDir}/example/AssertionsDemo.java[tags=user_guide]

documentation/src/test/java/example/AssertionsDemo.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,9 @@ void standardAssertions() {
4141
assertEquals(2, calculator.add(1, 1));
4242
assertEquals(4, calculator.multiply(2, 2),
4343
"The optional failure message is now the last parameter");
44-
assertTrue('a' < 'b', () -> "Assertion messages can be lazily evaluated -- "
45-
+ "to avoid constructing complex messages unnecessarily.");
44+
45+
// Lazily evaluates generateFailureMessage('a','b').
46+
assertTrue('a' < 'b', () -> generateFailureMessage('a','b'));
4647
}
4748

4849
@Test
@@ -160,6 +161,10 @@ private static String greeting() {
160161
return "Hello, World!";
161162
}
162163

164+
private static String generateFailureMessage(char a, char b) {
165+
return "Assertion messages can be lazily evaluated -- "
166+
+ "to avoid constructing complex messages unnecessarily." + (a < b);
167+
}
163168
}
164169
// end::user_guide[]
165170
// @formatter:on

0 commit comments

Comments
 (0)