DEV Community

Rafał Garbowski
Rafał Garbowski

Posted on • Originally published at rg9.dev

AssertJ custom representation of asserted object

I really enjoy asserting collections with AssertJ.
Usually it's safer and simpler to use containsExactlyInAnyOrder rather than asserting individual elements (collection.get(0)) - even if there is only one element, because it may change in the future.
The challenge starts when asserting collection containing complex objects, because constructing an entire object as expected element can be tedious.
To extract only certain properties, we can use .extracting(Foo::field1, Foo::field2).

        var players = List.of(
            new Player("Michael Jordan", new Team("Bulls")),
            new Player("Kobe Bryant", new Team("Lakers")));

        assertThat(players)
            .extracting(Player::name, player -> player.team().name())
            .containsExactly(
                tuple("Michael Jordan", "Bulls"),
                tuple("Kobe Bryant", "Lakers"));
Enter fullscreen mode Exit fullscreen mode

However, I tend to concatenate properties to string because I wasn't fond of working with tuples:

        assertThat(players)
            .extracting(player -> player.name() + " | " + player.team().name())
            .containsExactly("Michael Jordan | Bulls",
                "Kobe Bryant | Lakers");
Enter fullscreen mode Exit fullscreen mode

The reason is that, by default, AssertJ provides a generic "tuple" representation in the "actual" section.
When copied, this has to be manually adapted to Java code, which can be inconvenient.

For example:

Expecting actual:
  [("Michael Jordan", "Bulls"),
    ("Kobe Bryant" "Lakers")]
Enter fullscreen mode Exit fullscreen mode

What I want is an "easy-to-copy" representation of the asserted object:

Expecting actual:
  [tuple("Michael Jordan", "Bulls"),
    tuple("Kobe Bryant" "Lakers")]
Enter fullscreen mode Exit fullscreen mode

Fortunately, there's an easy way to globally fix this in 3 simple steps.

  1. Define a custom representation:
class CustomAssertJRepresentation extends StandardRepresentation {

    static final CustomAssertJRepresentation INSTANCE = new CustomAssertJRepresentation();

    @Override
    protected String toStringOf(Tuple tuple) {
        return "tuple" + super.toStringOf(tuple);
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Then add it to the global configuration:
public class CustomAssertJConfiguration extends Configuration {

    @Override
    public Representation representation() {
        return CustomAssertJRepresentation.INSTANCE;
    }

    @Override
    public String describe() {
        return "CustomAssertJConfiguration applied";
    }
}
Enter fullscreen mode Exit fullscreen mode
  1. Lastly, register the global config in this file: /src/test/resources/META-INF/services/org.assertj.core.configuration.Configuration which will contain:
my.package.CustomAssertJConfiguration
Enter fullscreen mode Exit fullscreen mode

Refer to the official documentation for more information: https://assertj.github.io/doc/#assertj-core-representation

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay