In JUnit, you can provide a custom message with assertThat to clarify assertion failures, which is useful when comparing objects with random or non-human-readable IDs.
Example in JUnit:
`
``java
assertThat("IDs should match", actualId, equalTo(expectedId));
In AssertJ, `assertThat` returns a chainable `Assert` object, but there doesn’t seem to be a built-in way to provide a custom message for failures.
Is there a way to add a descriptive failure message in AssertJ without creating custom assert classes?
In my projects, I usually use describedAs to add a clear message. It goes before the actual assertion:
import static org.assertj.core.api.Assertions.assertThat;
assertThat(actualId)
.describedAs("Expected ID to match the generated value")
.isEqualTo(expectedId);
If the assertion fails, the failure message will include your description, which is very helpful when IDs are random or not human-readable.
I often need dynamic messages with values included. describedAs supports formatting placeholders, which makes the failure message more informative:
assertThat(actualId)
.describedAs("Expected ID to be <%s> but was <%s>", expectedId, actualId)
.isEqualTo(expectedId);
This way, when the test fails, you see exactly what was expected and what was returned, without writing custom assert classes.
If you prefer a shorter, more readable chain, AssertJ also provides as() as an alias:
assertThat(actualId)
.as("Checking that the generated ID matches expected")
.isEqualTo(expectedId);
It behaves identically to describedAs, but I find as() cleaner for inline assertions in tests.