Chained assertions
There are many different ways to write AssertJ assertions. Having many assertions on the same object can decrease the readability. Chained assertions allow you to group multiple assertions on the same object into a single statement, making it much easier to read.
Limited expressiveness
JUnit 3, 4, 5 and 6 only provides basic assertions like assertTrue
, assertFalse
, assertEquals
, and assertNotNull
.
This makes tests verbose and harder to understand, especially when they fail.
- Before
- After
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 assertions makes the test longer and harder to read.
ChainedAssertJTest.java
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
class ChainedAssertJTest {
@Test
void bundle() {
List<Book> books = new Bundle().getBooks();
assertThat(books)
.hasSize(3)
.contains(
new Book("Effective Java", "Joshua Bloch", 2001),
new Book("Java Concurrency in Practice", "Brian Goetz", 2006),
new Book("Clean Code", "Robert C. Martin", 2008))
.doesNotContain(new Book("Java 8 in Action", "Raoul-Gabriel Urma", 2014));
}
}
tip
Using chained assertions makes the test more fluent and easier to read.