I am learning about unit testing and found that it is possible to use lambdas so that my error message is loaded only when the test fails, avoiding resource waste. However, IntelliJ displays a warning, suggesting that the approach is incorrect.
My code:
@Test
void test() {
var expected = "hello";
var actual = "world";
assertEquals(expected, actual, () -> "...error message...");
}
IntelliJ's warning message:
Excessive lambda usage
Use 'assertEquals' method without lambda
How can I deal with this warning avoiding resource waste?
According to the JUnit 5 user guide:
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.
Using a Supplier<String>
for the message can be useful when you have a computationally expensive computation for computing the message, for example if you are computing a lot of things to include in the error message.
assertEquals(expected, actual, () -> "error message, detail: " + computeSomethingThatShouldBeIncludedInTheLoggingMessage());
However, this isn't giving you any benefit if it's just a string literal. That one would have to be loaded with the class anyway and just passed to the test whereas a lambda has quite a bit of overhead (it pretty much has to load an additional class).
This is also noted in the section you quoted from the user guide saying that it can (meaning not always) improve performance if the construction of the message is computationally complex (or needs other resources) which isn't the case with a string literall that's in the constant pool at all.
That being said, I want to remind you that "premature optimization is the root of all evil". Don't randomly optimize stuff unless your profiler tells you that these parts are actually performance issues. And if your profiler detects something you want to optimize, make sure to benchmark it before and after your changes to compare the result. Don't write some code because you think it would be faster. Write the code that's more readable.