DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Java
  4. Introduction to AssertJ [Snippets]

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.

Helen Johnson user avatar by
Helen Johnson
·
Apr. 04, 18 · Code Snippet
Like (5)
Save
Tweet
Share
9.55K Views

Join the DZone community and get the full member experience.

Join For Free

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:

Apache Maven Testing Repository (version control) Java (programming language) Library Strings Advantage (cryptography) Clear (Unix) Data Types

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Simulating and Troubleshooting BLOCKED Threads in Kotlin [Video]
  • How To Build a Spring Boot GraalVM Image
  • Low-Code Development: The Future of Software Development
  • AWS CodeCommit and GitKraken Basics: Essential Skills for Every Developer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: