AssertJ – fluent assertions for Java

AssertJ – fluent assertions for Java

AssertJ is an open source Java library for writing fluent assertions in your test code. It’s an alternative to built-in assertions from the Junit testing framework or matchers from the Hamcrest library. It can help you write assertions that are more readable and closer to natural language. AssertJ API is also designed to be easily discoverable through IDE code completion.

Benefits of AssertJ

The most commonly used test assertions in Java are the ones from the Junit library, like assertEquals. The order of parameters in these assertions is important, but it is quite easy to get it wrong. The assertion will fail as expected, but it will produce a confusing error message:

assertEquals("actual", "expected");

Expected :actual
Actual :expected

AssertJ helps you to write assertions that are much closer to natural language. This makes them more readable and reduces the chance of writing them wrongly:


Another benefit of AssertJ is the fluent interface which enables the chaining of multiple assertions. Instead of writing multiple statements, you can write it like this:


This will fail with a helpful message:

  to contain:

Built-in assertions

AssertJ provides built-in assertions for many different types of objects. We’ve already seen assertions on String objects. Here is an example of an assertion on integers:

  .isBetween(100, 200);

Assertions on lists are quite powerful – this example shows how to filter a list of User objects on the user role and extract user names (using Java 8 features):

  .filteredOn(user -> user.getRole().equals("ADMIN"))
  .contains("user1", "user2");

Assertions on exceptions are also supported:

assertThatThrownBy(() -> { throw new RuntimeException("error"); })

Custom assertions

It’s also possible to write your own assertions – this is especially useful for your core domain model classes. You can write custom assertions manually or use the provided assertions generator. This will result in a domain specific language for use in tests. An example usage of custom assertions:



If you want to try the AssertJ library, you can get it via Maven:


Or if you use Gradle:

Why touch-typing is good for programmers

Related posts

Interconnect past and the future – monolith with microservice in mind

Interconnect past and the future – monolith with microservice in mind

Ingemark 07.01.2021.
Improved Java microservice logging with MDC

Improved Java microservice logging with MDC

Ingemark 22.12.2020.
Continuous Delivery and Code Quality

Continuous Delivery and Code Quality

Ingemark 18.12.2018.

By Clicking on Accept, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. For more details, please review our Privacy Policy.

Accept all