Video in progress
When is usingRecursiveComparison() useful in AssertJ, and what traps does it have?
It compares objects field by field instead of with equals: you can check an entity or DTO with no equals written against an expected object in a single line. The traps are excess ignoringFields, BigDecimal scale differences and Hibernate lazy proxies.
📖 Answer
The simple case: a service returns a DTO with 12 fields. Instead of 12 assertThat(...).isEqualTo(...) calls:
assertThat(actual)
.usingRecursiveComparison()
.ignoringFields("id", "createdAt")
.withComparatorForType(BigDecimal::compareTo, BigDecimal.class)
.isEqualTo(expected);
If there's a difference, AssertJ shows exactly which field path (items[1].price) didn't match.
The traps:
BigDecimal. new BigDecimal("10.0") and new BigDecimal("10.00") aren't equal by equals. When you compare a value returned from a numeric(12,2) column with one written by hand, the test fails. The withComparatorForType above fixes that.
Excess ignores. The ignoringFields list grows, and one day a field that's the whole point of the test ends up in it. Likewise ignoringExpectedNullFields() is handy, but it also silently skips fields forgotten in the expected object.
Entities and proxies. If you compare a Hibernate entity recursively, AssertJ walks into lazy associations too: with a closed session you get a LazyInitializationException, with an open one you get unexpected extra queries. Compare the DTO, not the entity, or limit it with comparingOnlyFields(...).
Collection order. A List is compared in order by default. If order doesn't matter, use ignoringCollectionOrder().
One useful side: if a new field is added to the expected object, the test fails on its own and you add it or ignore it deliberately. With a few hand-written asserts, that new field would silently go unchecked.
Sign up to mark studied questions and save your progress.