What it is
AssertJ is a fluent and rich assertion library for Java that allows developers to write readable and expressive unit test assertions. It provides a wide variety of assertions for core Java types, collections, exceptions, and more.
AssertJ provides a fluent API for assertions, allowing chaining of methods, clear error messages, and a wide range of assertions for objects, collections, maps, exceptions, and more. It integrates seamlessly with JUnit or TestNG.
Installation
Add org.assertj:assertj-core dependency in pom.xmlGetting started
The smallest useful thing you can do with it, and what each part means.
import static org.assertj.core.api.Assertions.*;
int result = 5;
assertThat(result).isEqualTo(5).isPositive();String text = "Hello World";
assertThat(text).startsWith("Hello").endsWith("World").contains("lo Wo");Advanced usage
Where the library earns its place over a simpler alternative.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
assertThat(numbers).hasSize(4).contains(2, 3).doesNotContain(5);assertThatThrownBy(() -> { Integer.parseInt("abc"); }).isInstanceOf(NumberFormatException.class).hasMessageContaining("For input string");class User { String name; int age; }
List<User> users = List.of(new User("Alice", 25), new User("Bob", 30));
assertThat(users).extracting(User::getName).containsExactly("Alice", "Bob");SoftAssertions softly = new SoftAssertions();
softly.assertThat(1).isEqualTo(2);
softly.assertThat("abc").startsWith("a");
softly.assertAll();Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- AssertionError
- Occurs when the actual value does not meet the expected condition. Check the test logic and input values.
- ClassNotFoundException for Assertions
- Ensure AssertJ core dependency is included in your project classpath.
Best practices
- Prefer AssertJ for readable and fluent assertions over standard JUnit assertions.
- Use chaining to combine multiple assertions on the same object for clarity.
- Leverage collection and property extraction methods for complex data structures.
- Use soft assertions when you want to evaluate multiple assertions and report all failures.
- Integrate with JUnit 5 or TestNG for seamless test execution.
Background
Why it exists, and what it was reacting to.
AssertJ was created to improve the readability and expressiveness of assertions in Java tests compared to standard JUnit assertions. Its fluent API allows for clear, chainable, and descriptive assertions, making tests easier to write and maintain.
