Explain Codes LogoExplain Codes Logo

Can you add a custom message to AssertJ assertThat?

java
assertions
custom-messages
assertj
Alex KataevbyAlex Kataev·Jan 31, 2025
TLDR
// Custom assert message. Because nothing sends the message of a failed test quite like a fruit-fight. import static org.assertj.core.api.Assertions.assertThat; String actual = "apple"; assertThat(actual) .withFailMessage("Expected fruit is 'orange' but got '%s'. It seems our taste buds are a bit confused.", actual) .isEqualTo("orange");

When informed by .withFailMessage(), your assertThat conditions become character witnesses, spilling the beans when an actual value fails to meet expectation. Checks your code stepping out of line? Woops, AssertJ has the snitch on speed dial.

AssertJ: delivering maximum customisation with minimum fuss

Adding context with the .as() method

AssertJ fluent API's .as() method, which supports String.format syntax, exists to lend your assertion some character. It precedes your assertion, providing valuable context, and is particularly useful when you're dealing with IDs and UUIDs, which are not always the most social creatures.

assertThat(actualUuid) .as("Verifying Player Session UUID. Alternatively, picking out a needle from a haystack.") .isEqualTo(expectedUuid);

Owning your error message with .withFailMessage()

Sometimes you need your error messages to be on brand. .withFailMessage() unequivocally lets you set a custom message that rivals Mum's homemade cookies.

assertThat(actualScore) // No 'expecting..'/'but was..' business here! .withFailMessage("Expected score to be at least %d, but was %d. How's that for a sad plot twist?", minScore, actualScore) .isGreaterThanOrEqualTo(minScore);

Reaping benefits from Java 11 and AssertJ

Get your two-piece suit ready! Java 11 and AssertJ got you covered:

var fruit = "apple"; assertThat(fruit) .as("Taste check") //it's like the Oscars, but for fruits .isEqualTo("orange");

Eloquent, sexy and efficient; just like you on a good coding day.

Understanding the difference for more effective usage

Choosing the right method for the right occasion

.as() or .withFailMessage()? Your choice should be governed by the context. .as() when you want your assertion to keep its identity yet wear a disguise. .withFailMessage() when you want a completely new custom message to throw in those unique details.

Mastering complex assertions

.overridingErrorMessage() takes modification on a rampage. Authorise it to override a predefined message, only to be your custom message's hero.

Going under the hood with AssertJ’s internals

Diving deeper into AssertJ, we’ll find that the .as() method is a part of the Descriptable interface, implemented by AbstractAssert. While .withFailMessage() resides inside the AbstractAssert class.