Over a million developers have joined DZone.

Writing Custom AssertJ Assertions [Snippet]

DZone's Guide to

Writing Custom AssertJ Assertions [Snippet]

If you've given AssertJ some thought but never really dived in, here's a quick guide to writing custom assertions to improve the quality of your test code.

· Java Zone ·
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

AssertJ is an alternative matching library to the widely used Hamcrest matchers. For my own projects, I, in fact, have changed to solely use AssertJ — I just find the fluid interfaces and extensibility quite appealing.

You can write custom assertions as follows.

Imagine a coffee with a strength and a drink type, such as Espresso or Latte. A custom CoffeeAssert validates coffee instances based on their custom business logic — in this case, their properties:

public class CoffeeAssert extends AbstractAssert<CoffeeAssert, Coffee> {

    public CoffeeAssert(Coffee actual) {
        super(actual, CoffeeAssert.class);

    public static CoffeeAssert assertThat(Coffee actual) {
        return new CoffeeAssert(actual);

    public CoffeeAssert hasType(Coffee.Type type) {

        if (actual.getType() != type) {
            failWithMessage("Expected the coffee type to be <%s> but was <%s>", type, actual.getType());

        return this;

    // hasStrength(Strength) omitted ...

    public CoffeeAssert isNotDecaf() {

        if (actual.getStrength() == Coffee.Strength.DECAF) {
            failWithMessage("Expected a coffee but got decaf!");

        return this;

Coffee instances can then simply be validated using the custom assertion. The static import of the assertThat has to refer to CoffeeAssert.

import static com.example.coffee.CoffeeAssert.assertThat;

Coffee coffee = new Coffee();


The use of custom assertions can vastly improve the quality of your test code.

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

java ,assertj ,custom assertions ,test code

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}