AssertJ – Fluent Assertions in Java

HOME

This tutorial describes the usage of the AssertJ – Fluent Assertions framework for writing tests in Java.

Introduction to AssertJ

The AssertJ project provides fluent assertion statements for test code written in Java. These assert statements are typically used with Java JUnit tests. 

AssertJ is composed of several modules:

A core module to provide assertions for JDK types (String, Iterable, Stream, Path, File, Map…​)
1. A Guava module to provide assertions for Guava types (Multimap, Optional…​)
2. A Joda Time module to provide assertions for Joda Time types (DateTime, LocalDateTime)
3. A Neo4J module to provide assertions for Neo4J types (Path, Node, Relationship…​)
4. A DB module to provide assertions for relational database types (Table, Row, Column…​)
5. A Swing module provides a simple and intuitive API for functional testing of Swing user interfaces

What is AssertJ Core?

AssertJ is a Java library that provides a rich set of assertions and truly helpful error messages, improves test code readability, and is designed to be super easy to use within any IDE.

AssertJ Core major versions depend on different Java versions:

  • AssertJ Core 3.x requires Java 8 or higher
  • AssertJ Core 2.x requires Java 7 or higher

AssertJ Core 3.x includes all AssertJ Core 2.x features and adds Java 8 specific ones (like exception assertions with lambdas).

Maven

<dependency>
    <groupId>org.assertj</groupId>
    <artifactId>assertj-core</artifactId>
    <version>3.22.0</version>
    <scope>test</scope>
</dependency>

Gradle

testImplementation 'org.assertj:assertj-core:3.22.0'

The Assertions class is the only class you need to start using AssertJ, it provides all the methods you need.

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

Verify that age is greater or equal to 50. This assertion will fail

int age = 20;
assertThat(age).isGreaterThanOrEqualTo(30);

There is another way to perform the same test. Don’t import the static package.

import org.assertj.core.api.Assertions;
int age = 20;

// Verify that age is greater or equal to 50
Assertions.assertThat(age).isGreaterThanOrEqualTo(30);

This assertion will pass.

int age = 50;

// Verify that age is greater or equal to 50
Assertions.assertThat(age).isGreaterThanOrEqualTo(30);

2. Array Assertions

For an Iterable or an Array there are multiple ways of asserting that their content exist. One of the most common assertions would be to check if an Iterable or Array contains a given element:

int age = 30;
List<Integer> ages = Arrays.asList(20, 25, 33, 45);

// Verify that ages list contains age(30) or not
Assertions.assertThat(ages).contains(age);

Verify if a list is empty or not

	List<String> names = Arrays.asList("Here", "Keep", "Ugly", "door", "time");

   @Test
	public void assertJAssertionsExample8() {
		Assertions.assertThat(names).isEmpty();

	}

Verify if a List starts with a given character. For example “Ugly”:

	List<String> names = Arrays.asList("Here", "Keep", "Ugly", "door", "time");

	@Test
	public void assertJAssertionsExample8() {

		// Verify that ages list contains age(30) or not
		Assertions.assertThat(names).startsWith("Ugly");

	}

Assert the size of the list

List<Integer> ages = Arrays.asList(20, 25, 33, 45);

// Verify that list ages contains 5 elements
Assertions.assertThat(ages).hasSize(5);

Chaining of assertions

AssertJ allows you to be concise by chaining multiple assertions.

int age = 30;
List<Integer> ages = Arrays.asList(20, 25, 33, 45);

// Verify that the list of age contains 20, and size of list is 4 and match the
// values of all elements
Assertions.assertThat(ages).contains(20).hasSize(4).allMatch(a -> a >= 10 && a <= 30);

3. Assertion description

It is often valuable to describe the assertion performed, especially for boolean assertions, where the default error message just complains that it got false instead of true (or vice versa).

You can set such a description as (String description, Object…​ args) but remember to do it before calling the assertion otherwise it is simply ignored as a failing assertion breaks the chained calls.

Example of a failing assertion with a description:

String name = "Happy Days are here";
Assertions.assertThat(name).as("check name").startsWith("Life");

The error message starts with the given description in [check name]

4. Assertions for Date

AssertJ provides special assertions for the Java date class.

LocalDateTime date1 = LocalDate.of(1992, 2, 14).atStartOfDay();
LocalDateTime date2 = LocalDate.of(1998, 1, 1).atStartOfDay();
Assertions.assertThat(date1).isEqualTo(date2);

LocalDateTime isAfter

LocalDateTime date1 = LocalDate.of(1992, 2, 14).atStartOfDay();
LocalDateTime date2 = LocalDate.of(1998, 1, 1).atStartOfDay();
Assertions.assertThat(date1).isAfter(date2);

LocalDateTime isBefore

LocalDateTime date1 = LocalDate.of(2025, 2, 14).atStartOfDay();
Assertions.assertThat(date1).isBefore(LocalDateTime.now());

5. Soft Assertions

Soft assertions AssertJ collects all assertion errors instead of stopping at the first one. Since soft assertions don’t fail at the first error, you need to tell AssertJ when to report the captured assertion errors, we are using assertAll().

SoftAssertions softly = new SoftAssertions();

softly.assertThat("George Martin").as("great authors").isEqualTo("JK Rowling");
softly.assertThat(42).as("comparison").isGreaterThan(120);
softly.assertThat("50").isEqualTo("23");

// Don't forget to call assertAll() otherwise no assertion errors are reported!
softly.assertAll();

6. Object Assertions

Objects can be compared in various ways, either to determine the equality of two objects or to examine the fields of an object.

public class AssertJEmployee {

	String name;
	int age;
	float salary;

	public AssertJEmployee(String name, int age, float salary) {
		super();
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public float getSalary() {
		return salary;
	}

	public void setSalary(float salary) {
		this.salary = salary;
	}

}
@Test
public void test() {

	AssertJEmployee emp1 = new AssertJEmployee("Tim", 24, 24000);
	AssertJEmployee emp2 = new AssertJEmployee("Tim", 20, 24000);

	Assertions.assertThat(emp1).usingRecursiveComparison().isEqualTo(emp2);
}

In the below example, we have used isEqualTo() method that compares object references. We can see that both objects are the same but have different references. So, the assertion fails here.

@Test
public void test() {

	AssertJEmployee emp1 = new AssertJEmployee("Tim", 24, 24000);
	AssertJEmployee emp2 = new AssertJEmployee("Tim", 24, 24000);

	Assertions.assertThat(emp1).isEqualTo(emp2);
}

Congratulation! We are able to understand the use of AssertJ. Happy Learning!!

Leave a comment