Java’s AssertJ: The Secret Weapon for Painless Testing
Writing clean and expressive tests with Java’s AssertJ library. Let’s learn how to test collections, primitives, exceptions, and domain objects!
In this article, we’ll discuss some features of Java’s AssertJ library. We’ll see how easy it is to test various types of data and to understand what went wrong when the tests are failing.
Moreover, we’ll learn how to create our own custom asserts based on the domain models, and use them to improve the readability of our tests.
1. Testing Collections
Let’s assume we want to write an assertion to check that a list contains two exact values. In most cases, I have seen code using the static assertEquals method0 imported from org.junit.jupiter.api.Assertions:
// import static org.junit.jupiter.api.Assertions.assertEquals;
@Test
void test() {
List<Integer> evenNumbers = List.of(1, 2, 3, 4, 5).stream()
.filter(nr -> nr % 2 == 0)
.toList();
assertEquals(2, evenNumbers.size());
assertEquals(2, evenNumbers.get(0));
assertEquals(4, evenNumbers.get(1));
}
This assertion has 2 problems: first, it is hard to understand, and we cannot quickly say what is being tested, especially if the use case is a bit more complex.