Skip to content

Commit 3646b7d

Browse files
chris-carneiromarcphilipp
authored andcommitted
Document benefits of messageSupplier in Assertions (#3938)
Resolves #3153. (cherry picked from commit 3b85a03)
1 parent 6b9f15d commit 3646b7d

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

Lines changed: 7 additions & 0 deletions
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

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)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy