You can use AssertJ with JUnit to write more readable, fluent assertions than standard JUnit assertions.
1. Add AssertJ Dependency
If you use Maven:
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.26.3</version>
<scope>test</scope>
</dependency>
If you use Gradle:
testImplementation("org.assertj:assertj-core:3.26.3")
2. Use AssertJ in a JUnit Test
Import assertThat statically:
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class UserServiceTest {
@Test
void shouldReturnUserName() {
String name = "Alice";
assertThat(name)
.isNotNull()
.startsWith("A")
.endsWith("e")
.hasSize(5);
}
}
3. AssertJ vs. JUnit Assertions
JUnit:
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
assertEquals("Alice", name);
assertTrue(name.startsWith("A"));
AssertJ:
import static org.assertj.core.api.Assertions.assertThat;
assertThat(name)
.isEqualTo("Alice")
.startsWith("A");
AssertJ reads more naturally and usually gives better failure messages.
4. Common AssertJ Examples
Strings
assertThat(email)
.isNotBlank()
.contains("@")
.endsWith(".com");
Numbers
assertThat(price)
.isPositive()
.isGreaterThan(10)
.isLessThanOrEqualTo(100);
Collections
assertThat(users)
.hasSize(3)
.extracting(User::getName)
.containsExactly("Alice", "Bob", "Charlie");
Objects
assertThat(user)
.isNotNull()
.extracting(User::getName, User::getEmail)
.containsExactly("Alice", "[email protected]");
Exceptions
assertThatThrownBy(() -> userService.findById(-1L))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("id");
Or with JUnit + AssertJ:
IllegalArgumentException exception =
assertThrows(IllegalArgumentException.class, () -> userService.findById(-1L));
assertThat(exception)
.hasMessageContaining("id");
5. Example with Spring/JUnit Test
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class CalculatorTest {
@Test
void shouldAddNumbers() {
Calculator calculator = new Calculator();
int result = calculator.add(2, 3);
assertThat(result).isEqualTo(5);
}
}
6. Helpful AssertJ Tips
Use as() to describe assertions:
assertThat(user.getEmail())
.as("user email should be valid")
.contains("@");
Use recursive comparison for objects:
assertThat(actualUser)
.usingRecursiveComparison()
.isEqualTo(expectedUser);
Use containsExactlyInAnyOrder() when order does not matter:
assertThat(roles)
.containsExactlyInAnyOrder("ADMIN", "USER");
Recommended Pattern
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
@Test
void shouldDoSomething() {
// arrange
User user = new User("Alice");
// act
String result = user.getName();
// assert
assertThat(result).isEqualTo("Alice");
}
In short: add assertj-core, statically import assertThat, and replace basic JUnit assertions with fluent AssertJ assertions for clearer and more expressive tests.
