# 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");
Use a Java Refactoring Tool
No license required
You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.
System-wide Refactoring
Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.