Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document benefits of messageSupplier in Assertions #3938

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions documentation/src/docs/asciidoc/user-guide/writing-tests.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>`.

When using a `Supplier<String>` (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]
Expand Down
9 changes: 7 additions & 2 deletions documentation/src/test/java/example/AssertionsDemo.java
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Loading