# Shift AssertJ Description Before Assertion

# Description

AssertJ provides methods for setting descriptions or error messages of assertions, e.g.:

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:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID ShiftAssertJDescriptionBeforeAssertion
First seen in jSparrow version 4.6.0
Minimum Java version 7
Remediation cost 5 min
Links