Can you add a custom message to AssertJ assertThat?
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.
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.
Reaping benefits from Java 11 and AssertJ
Get your two-piece suit ready! Java 11 and AssertJ got you covered:
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.
Was this article helpful?