When writing tests, failing fast isnโt always the best. Sometimes, you want to collect all assertion failures in one go. Thatโs where AssertJ SoftAssertions come in ๐ก
๐ธ WHAT IS ASSERTJ? ๐ค
- AssertJ is a fluent assertion library for Java, making your tests:
- More readable (natural language style)
- More expressive (rich API, better error messages)
- More maintainable (chainable, fluent methods)
๐ธ CODE EXAMPLE ๐ป
class UserTest {
@Test
void testUserProperties() {
User user = new User("Alice", 25, "Paris");
SoftAssertions softly = new SoftAssertions();
softly.assertThat(user.getName()).isEqualTo("Bob");
softly.assertThat(user.getAge()).isGreaterThan(30);
softly.assertThat(user.getCity()).isEqualTo("London");
softly.assertAll(); // Collects and reports all failures ๐จ
}
}
Instead of failing on the first mismatch, AssertJ reports all assertion errors together ๐
๐ธ ADVANTAGES ๐
- Detect multiple issues in one test run
- Provide comprehensive feedback to developers
- Reduce test re-runs ๐
- Keep test code concise & elegant
๐ธ TAKEAWAYS ๐
- Use AssertJ to write fluent, readable, and powerful assertions
- Use SoftAssertions when you want to gather multiple failures at once
- Cleaner tests = faster debugging = happier developers ๐
#Java #Testing #AssertJ #UnitTesting #CleanCode #TDD