# Shift AssertJ Description Before Assertion
# Description
AssertJ provides methods for setting descriptions or error messages of assertions, e.g.:
- as (opens new window)
- describedAs (opens new window)
- withFailMessage (opens new window)
- overridingErrorMessage (opens new window)
These methods should always be invoked before the actual assertion they intend to describe, otherwise, they have no effect.
This rule, swaps the invocation of the assertion methods with the invocation of the methods setting descriptions or the error messages for the corresponding assertions. See the code examples below.
Requirements
- AssertJ
# Benefits
Improves the readability of assertion failure messages.
# Tags
# Code Changes
# Shifting describedAs
Pre
assertThat(user.getName())
.isEqualTo("John")
.describedAs("Asserting the correct username");
Post
assertThat(user.getName())
.describedAs("Asserting the correct username")
.isEqualTo("John");
# Shifting as
Pre
assertThat(user.getName())
.isEqualTo("John")
.as("Asserting the correct username");
Post
assertThat(user.getName())
.as("Asserting the correct username")
.isEqualTo("John");
# Shifting withErrorMessage
Pre
assertThat(user.getName())
.isEqualTo("John")
.withErrorMessage("Unexpected username");
Post
assertThat(user.getName())
.withErrorMessage("Unexpected username")
.isEqualTo("John");
# Shifting overridingErrorMessage
Pre
assertThat(user.getName())
.isEqualTo("John")
.overridingErrorMessage("Unexpected username");
Post
assertThat(user.getName())
.overridingErrorMessage("Unexpected username")
.isEqualTo("John");
🛠️ Auto-refactor Available
You can auto refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:
Need help? Check out our installation guide.