I’m using AssertJ in a test suite and want to include meaningful debug messages when assertions fail, similar to JUnit’s assertThat(reason, matcher). The objects I’m comparing often have UUIDs or non-human-readable data, so a custom message would help understand failures. Is there a built-in way in AssertJ to provide a custom message for assertThat without creating a separate assertion class for each type?
From my experience, the easiest way to add a custom failure message in AssertJ is using the .as() method (or its alias .describedAs()). This allows you to attach a description to the assertion, which will show up when the test fails:
import static org.assertj.core.api.Assertions.assertThat;
String actual = getUuidFromService();
String expected = "123e4567-e89b-12d3-a456-426614174000";
assertThat(actual)
.as("Check UUID returned by service")
.isEqualTo(expected);
This will give you a clearer error message in case of failure, like:
[Check UUID returned by service]
Expecting actual: ... to be equal to: ...
It’s a built-in way to add context and works for any type you’re asserting. It’s super helpful for quick debugging, and you don’t need to create a custom assertion class for each type.
Absolutely! The .as() method is great, but you can really take it a step further by making your failure message more informative. You can include the actual and expected values directly in the message, which makes debugging even easier. Here’s an enhanced version:
assertThat(actual)
.as("Expected UUID %s but got %s", expected, actual)
.isEqualTo(expected);
With this, if the assertion fails, you’ll get a more detailed error message like:
Expected UUID 123e4567-e89b-12d3-a456-426614174000 but got 123e4567-e89b-12d3-a456-426614174001
This can save you a lot of time by showing you exactly what went wrong without needing to sift through logs. It’s a little more detailed than just using .as() on its own.
I’ve used both .as() and .withFailMessage() in my tests, and it really comes down to personal preference. I’ve found that .withFailMessage() can sometimes be a little cleaner for certain cases. Here’s how you can use it to customize failure messages:
assertThat(actual)
.withFailMessage("UUID mismatch! Expected %s, found %s", expected, actual)
.isEqualTo(expected);
With assertj withfailmessage, you get a direct, concise failure message. While .as() is more of a description of the assertion itself, .withFailMessage() focuses purely on the failure message. Both are useful, so it’s up to you whether you want to use .as() for an overarching description or .withFailMessage() for a more focused failure explanation.