sebastiandaschner blog


Write custom AssertJ assertions

#java #testing monday, january 01, 2018

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) {
        isNotNull();

        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() {
        isNotNull();

        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();
coffee.setStrength(Strength.STRONG);
coffee.setType(Type.ESPRESSO);

assertThat(coffee)
    .hasType(Type.ESPRESSO)
    .isNotDecaf();

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

This post was reposted from my newsletter issue 012

 

Found the post useful? Subscribe to my newsletter for more free content, tips and tricks on IT & Java: