Skip to content

Commit 3b85a03

Browse files
Document benefits of messageSupplier in Assertions (#3938)
Resolves #3153.
1 parent 59f216c commit 3b85a03

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

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

+7
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,13 @@ 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 optionally accept the assertion message as their third parameter, which
297+
can be either a `String` or a `Supplier<String>`.
298+
299+
When using a `Supplier<String>` (e.g., a lambda expression), the message is evaluated
300+
lazily. This can provide a performance benefit, especially if message construction is
301+
complex or time-consuming, as it is only evaluated when the assertion fails.
302+
296303
[source,java,indent=0]
297304
----
298305
include::{testDir}/example/AssertionsDemo.java[tags=user_guide]

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

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