Skip to main content

Chained and combined assertions

AssertJ's fluent API lets you chain multiple assertions on the same object, and combine checks for multiple elements into a single statement. This makes tests more concise, more readable, and produces better failure messages.

Chain assertions on the same object​

Having many separate assertThat() calls on the same object decreases readability. Chain them instead.

ChainedAssertJTest.java
import java.util.List;

class ChainedAssertJTest {

@Test
void bundle() {
List<Book> books = new Bundle().getBooks();

assertThat(books).isNotNull();
assertThat(books.size()).isEqualTo(3);
assertThat(books).contains(new Book("Effective Java", "Joshua Bloch", 2001));
assertThat(books).contains(new Book("Java Concurrency in Practice", "Brian Goetz", 2006));
assertThat(books).contains(new Book("Clean Code", "Robert C. Martin", 2008));
assertThat(books).doesNotContain(new Book("Java 8 in Action", "Raoul-Gabriel Urma", 2014));
}
}
warning

The long list of separate assertions makes the test longer and harder to read.

Combine checks for multiple elements​

When checking for multiple elements, pass them all to a single assertion instead of repeating assertTrue().

AssertListContains.java
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertTrue;

class AssertListContains {

List<String> list = List.of("a", "b", "c");

@Test
void assertMultipleElements() {
assertTrue(list.contains("a"));
assertTrue(list.contains("b"));
assertTrue(list.contains("c"));
}
}
warning

Multiple assertTrue() calls are verbose and stop at the first failure, hiding subsequent issues.