Return to site

🤩 ASSERTJ SOFT ASSERTIONS: CLEANER, SAFER TESTING ✅

· assertj,java,testing
Section image

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