Fork me on GitHub

Introduction

AssertJ core is a Java library that provides a fluent interface for writing assertions. Its main goal is to improve test code readability and make maintenance of tests easier.

During this workshop you will use AssertJ 3.X.

For more information, please visit:

Exercise

In this part of the workshop you will refactor and extends tests of InMemoryBookRepositoryTest class. You will change some JUnit assertions to fluent assertions and also add new ones. You should start by opening the InMemoryBookRepositoryTest.java file.

AssertJ Basics

AssertJ provides org.assertj.core.api.Assertions class which defines assertThat method. It allows you to get list of all available assertions for the tested object. Bellow is a list of the equivalent verification conditions. You can see that AssertJ assertions are much more concise for complex operations than JUnit assertions.

JUnit (Assert) AssertJ (Assertions)
assertNotNull(obj);
assertThat(obj).isNotNull();
assertTrue(bool);
assertThat(bool).isTrue();
assertNotNull(collection);
assertEquals(2, collection.size());
assertThat(collection).hasSize(2);
assertNotNull(collection);
assertEquals(2, collection.size());
assertTrue(collection.contains(obj1));
assertTrue(collection.contains(obj2));
assertThat(collection).containsExactly(obj1, obj2);