Core Java

Write custom AssertJ assertions

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:

Published on Java Code Geeks with permission by Sebastian Daschner, partner at our JCG program. See the original article here: Write custom AssertJ assertions

Opinions expressed by Java Code Geeks contributors are their own.

Sebastian Daschner

Sebastian Daschner is a self-employed Java consultant and trainer. He is the author of the book 'Architecting Modern Java EE Applications'. Sebastian is a Java Champion, Oracle Developer Champion and JavaOne Rockstar.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button