Assertions
TL;DR
- Assertions are the core mechanism in testing that validates the outcome. If an assertion evaluates to
false, it throws anAssertionError, failing the test. - JUnit 5 provides built-in assertions (
assertEquals,assertTrue). - The industry standard has largely shifted to using AssertJ or Hamcrest for highly readable, fluent assertion APIs.
Concept
The “Assert” phase is the final step of a unit test.
JUnit 5 Assertions are straightforward but lack readability for complex objects. (assertEquals(expected, actual)).
AssertJ is a 3rd-party library (included by default in Spring Boot) that uses a Fluent API. You start with assertThat(actual) and chain methods. It reads like a natural English sentence: assertThat(user.getName()).startsWith("A").endsWith("z"). Furthermore, when an AssertJ assertion fails, its error messages are vastly more descriptive than JUnit’s.
Examples
import org.junit.jupiter.api.Test;
// JUnit Assertions
import static org.junit.jupiter.api.Assertions.*;
// AssertJ Assertions
import static org.assertj.core.api.Assertions.*;
import java.util.List;
class AssertionDemoTest {
@Test
void testWithJUnit5() {
String name = "Alice";
List<String> colors = List.of("Red", "Blue");
// The expected value ALWAYS comes first in JUnit!
assertEquals("Alice", name);
assertTrue(colors.contains("Red"));
// Asserting an Exception in JUnit 5
assertThrows(NullPointerException.class, () -> {
String s = null;
s.length();
});
}
@Test
void testWithAssertJ() {
String name = "Alice";
List<String> colors = List.of("Red", "Blue");
// The ACTUAL value ALWAYS comes first in AssertJ! Reads like English.
assertThat(name).isEqualTo("Alice")
.startsWith("Al")
.hasSize(5);
// AssertJ is incredibly powerful for Collections
assertThat(colors).contains("Red")
.doesNotContain("Green")
.hasSize(2);
// Asserting an Exception in AssertJ
assertThatThrownBy(() -> {
String s = null;
s.length();
}).isInstanceOf(NullPointerException.class);
}
}
Interview Questions
Q: What is assertAll() in JUnit 5?
A: Normally, if a test has 3 assertions, and the first one fails, the test halts immediately. You fix it, run it again, and find out the second one failed. assertAll("Group", () -> assertEquals(...), () -> assertTrue(...)) evaluates all provided assertions before halting. If multiple assertions fail, it reports all of them at once in a MultipleFailuresError. (AssertJ offers the exact same feature using SoftAssertions).
Q: Why is AssertJ preferred over standard JUnit assertions for Collections?
A: If you want to check if a List contains an item in JUnit, you write assertTrue(list.contains("Red")). If this fails, JUnit prints: Expected: true, Actual: false. You have no idea what the list actually contained!
If you use AssertJ: assertThat(list).contains("Red"). If it fails, AssertJ prints: Expecting ArrayList: ["Blue", "Yellow"] to contain: ["Red"] but could not find: ["Red"]. This instant visibility saves countless hours of debugging.