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

Introduction to AssertJ [Snippets]

DZone's Guide to

Introduction to AssertJ [Snippets]

Want a simple introduction to the ever-helpful AssertJ? See how to put this popular library to use in your projects to simplify your test code.

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

AssertJ is a library used to provide assert statements for Java. It is a fork of the FEST-Assert library.

assertThat() is the main method to be used.

// unique entry point to get access to all assertThat methods and utility methods (e.g. entry)
import static org.assertj.core.api.Assertions.*;

// common assertions
assertThat(frodo.getName()).isEqualTo("Frodo");
assertThat(frodo).isNotEqualTo(sauron)
                 .isIn(fellowshipOfTheRing);

// String specific assertions
assertThat(frodo.getName()).startsWith("Fro")
                           .endsWith("do")
                           .isEqualToIgnoringCase("frodo");

// collection specific assertions
assertThat(fellowshipOfTheRing).hasSize(9)
                               .contains(frodo, sam)
                               .doesNotContain(sauron);

// using extracting magical feature to check fellowshipOfTheRing characters name :)
assertThat(fellowshipOfTheRing).extracting("name").contains("Boromir", "Gandalf", "Frodo", "Legolas")
                                                  .doesNotContain("Sauron", "Elrond");

// map specific assertions, ringBearers initialized with the elves rings and the one ring bearers.
assertThat(ringBearers).hasSize(4)
                       .contains(entry(oneRing, frodo), entry(nenya, galadriel))
                       .doesNotContainEntry(oneRing, aragorn);


AssertJ's Advantages

AssertJ contains a large number of statements and error messages and helps to simplify test code, thus, improving its readability.

Date today = new Date();
assertTrue((birthday.getTime() > today.getTime()));
assertThat(birthday).isBefore(today);


It also provides clear messages about test errors:

List<String> list = new ArrayList<>();
assertTrue(list.contains("abc"));
->
java.lang.AssertionError at ...

assertThat(list).contains("abc");
->
java.lang.AssertionError:
    Expecting:
         <[]>
        to contain:
         <["abc"]>
        but could not find:
         <["abc"]>


Project Creation

Maven

Assert artifacts are in a central Maven repository.

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <!-- use 2.9.0 for Java 7 projects -->
    <version>3.9.0</version>
    <scope>test</scope>
</dependency>


Gradle

To use Grable (a central Maven repository is used):

testCompile 'org.assertj:assertj-core:3.9.0'


Or 2.9.0 version for projects with Java 7 used:

testCompile 'org.assertj:assertj-core:2.9.0'


To use AssertJ methods, static imports should be added:

import static org.assertj.core.api.Assertions.assertThat; // main one
import static org.assertj.core.api.Assertions.atIndex; // for List assertions
import static org.assertj.core.api.Assertions.entry; // for Map assertions
import static org.assertj.core.api.Assertions.tuple; // when extracting several properties at once
import static org.assertj.core.api.Assertions.fail; // use when writing exception tests
import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; // idem
import static org.assertj.core.api.Assertions.filter; // for Iterable/Array assertions
import static org.assertj.core.api.Assertions.offset; // for floating number assertions
import static org.assertj.core.api.Assertions.anyOf; // use with Condition
import static org.assertj.core.api.Assertions.contentOf; // use with File assertions


Or one static import:

import static org.assertj.core.api.Assertions.*;


The main methods to be used is assertThat():

assertThat(objectUnderTest). // code completion -> assertions specific to objectUnderTest


Example of String assertions:

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
test automation ,assertj ,java ,java testing

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}