Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 

Topics:
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 }}