AssertJ Tutorial for Fluent Assertions in Java Tests
Learn AssertJ: fluent assertions for values, strings, collections, exceptions and objects, soft assertions, custom messages and extracting fields.

JUnit's assertEquals(expected, actual) works, and when it fails it says little. AssertJ reads like a sentence, offers a method for nearly every check you would otherwise write by hand, and produces failure messages that describe the difference. It ships inside spring-boot-starter-test and can be added to any project. This tutorial covers the core of AssertJ 3.x with JUnit 5: values and strings, collections, objects, exceptions, soft assertions and descriptions. It is organised by what you are checking, so you can come back to the section you need. The styles are compared in JUnit versus AssertJ versus Hamcrest.
Setup
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>import static org.assertj.core.api.Assertions.*;With Spring Boot the version is managed, so the dependency has no version. A single static import of Assertions.* gives you assertThat and the exception helpers. One practical point: ensure that no other assertThat, from JUnit or Hamcrest, is imported in the same file, or the IDE may complete the wrong one and offer a smaller set of methods.
Values and strings
assertThat(order.total()).isEqualByComparingTo("25.00");
assertThat(order.status()).isEqualTo(Status.PAID);
assertThat(customer.email())
.isNotBlank()
.endsWith("@example.com")
.doesNotContain(" ");
assertThat(price).isBetween(BigDecimal.ONE, BigDecimal.TEN);
assertThat(score).isGreaterThan(0.5).isLessThanOrEqualTo(1.0);isEqualByComparingTo compares BigDecimal values ignoring scale, which avoids the classic failure where 2.0 and 2.00 are not equal. Chaining checks on the same subject keeps the test compact, and each link in the chain is evaluated in order, so the first failing check is reported. The failing output names the value and the rule:
Expecting actual:
"[email protected]"
to end with:
"@example.com"Compare that with a JUnit assertTrue(email.endsWith(...)), which reports only that the condition was false. For strings AssertJ also has containsIgnoringCase, matches for a regular expression and isEqualToIgnoringWhitespace, which cover most of the cases where people write a helper.
Collections
List<String> names = List.of("ada", "grace", "linus");
assertThat(names)
.hasSize(3)
.contains("grace")
.containsExactly("ada", "grace", "linus") // exact order
.containsExactlyInAnyOrder("linus", "ada", "grace")
.doesNotHaveDuplicates()
.allMatch(n -> n.length() > 2);
assertThat(map).containsEntry("a", 1).containsKeys("a", "b");containsExactly checks both content and order, containsExactlyInAnyOrder ignores order but still requires the same elements, and contains checks only that the listed items are present. Choosing the strictest one that is true keeps a test from passing by accident. For lists of objects, extract the field you care about:
assertThat(orders)
.extracting(Order::customer, Order::total)
.containsExactly(tuple("ada", money("25.00")), tuple("bob", money("10.00")));
assertThat(orders).filteredOn(o -> o.status() == Status.OPEN).hasSize(2);extracting replaces a loop that collects fields into a list, and tuple groups several fields so they are compared together. filteredOn narrows the collection before the next check. When a collection assertion fails, AssertJ prints the actual contents, so you rarely need to add a log line to see what the list held.
Objects
assertThat(actualCustomer).usingRecursiveComparison().isEqualTo(expectedCustomer);
assertThat(actualCustomer).usingRecursiveComparison().ignoringFields("id", "createdAt").isEqualTo(expected);Recursive comparison compares two objects field by field without relying on equals, which is what you want for DTOs and entities whose equals covers only an id. Ignore the fields that vary, such as generated ids and timestamps, and the failure message lists exactly which fields differed with both values. It follows nested objects and collections, so a deep structure needs one line, not twenty.
Exceptions
assertThatThrownBy(() -> service.pay(order, Money.of("1.00")))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("amount must equal the total");
assertThatExceptionOfType(PaymentDeclinedException.class)
.isThrownBy(() -> gateway.charge(order))
.withMessage("insufficient funds")
.withNoCause();
assertThatCode(() -> service.validate(order)).doesNotThrowAnyException();All three forms keep the check in one chain: what was thrown, its message and its cause. That is clearer than a try and catch with a fail call, and tighter than assertThrows when you want to check the message and cause in the same breath. The JUnit way is in assertThrows and assertAll. assertThatCode is the right tool for "this must not throw", where the alternative is a test with no assertions at all.
Soft assertions
SoftAssertions.assertSoftly(soft -> {
soft.assertThat(user.name()).isEqualTo("ada");
soft.assertThat(user.age()).isGreaterThan(18);
soft.assertThat(user.roles()).contains("admin");
});All three checks run, and the failure report lists every problem together. Use them when the assertions are independent facts about one result, so a single run tells you everything that is wrong. Do not use them to check a sequence where later steps depend on earlier ones, because a failure in step one makes the rest meaningless.
Messages and descriptions
assertThat(order.total()).as("total of order %s", order.id()).isEqualByComparingTo("25.00");as(...) adds context to the failure message and must come before the check it describes. Use it where the value alone does not explain the check, for instance inside a loop over many items. Custom assertions for domain objects, such as assertThat(order).isPaid(), can be generated or written by hand and make tests read in business language; the writing of one is described in custom assertions.
Other useful assertions
Files and paths have assertThat(path).exists().isRegularFile(). Optionals have assertThat(optional).contains(x). Time has assertThat(instant).isCloseTo(now, within(1, ChronoUnit.SECONDS)), the correct way to compare with a clock that moves. JSON strings can be compared with a JSON library, and futures have assertThat(future).succeedsWithin(Duration.ofSeconds(1)). The collection and exception helpers are expanded in collections and exceptions.
Custom comparison and tolerances
Real data seldom compares exactly. Floating-point values need a tolerance: assertThat(result).isCloseTo(3.14, within(0.01)). Dates from a clock that moves need a window: isCloseTo(expected, within(2, ChronoUnit.SECONDS)). Objects whose equals is too strict or too loose can be compared with a custom comparator for one field: usingRecursiveComparison().withComparatorForType(BigDecimal::compareTo, BigDecimal.class) treats 2.0 and 2.00 as equal everywhere in the object graph. These options keep the test honest about what matters and stop it from failing on noise that the business does not care about.
Reading a failure
AssertJ failures have a consistent shape: the word "Expecting", the actual value, the condition in words and the expected value. Train yourself to read them in that order. A message that starts with "Expecting actual not to be null" says the subject was null, and no later check ran. A message listing "elements not found" and "elements not expected" for containsExactlyInAnyOrder tells you precisely which side has the extra or missing item. If a message is still unclear, add as(...) with context rather than a comment in the test.
With JUnit and Mockito
AssertJ replaces only the assertion style, not the test framework. It combines with JUnit 5 and with Mockito mocks, whose verification calls stay as they are. Pick one assertion style per project so the tests read alike, and let the formatter or a lint rule ban the others if the team keeps drifting.
When plain JUnit is enough
For a few simple equality checks, JUnit's built-in assertions suffice, and a new dependency is not worth it in a tiny project. Hamcrest is the older matcher library that AssertJ replaces for most uses. The reference is the AssertJ documentation, and the core Javadoc lists every method.


