Concept Explanation
A test is only useful if it fails loudly for the right reason. That comes down to two things: picking the right assertion, and setting up state correctly for each test.
The Assertion Toolbox
import static org.junit.jupiter.api.Assertions.*;
assertEquals(15, calc.add(10, 5));
assertNotEquals(0, total);
assertTrue(user.isActive());
assertNull(cache.get("missing"));
assertSame(expected, actual); // same object reference
assertArrayEquals(new int[]{1,2}, result);
assertIterableEquals(List.of("a","b"), names);
Testing that something fails is just as important:
@Test
void rejectsNegativeAmount() {
IllegalArgumentException ex = assertThrows(
IllegalArgumentException.class,
() -> account.withdraw(-50));
assertEquals("Amount must be positive", ex.getMessage());
}
Group related checks so you see all failures at once, not just the first:
@Test
void userIsFullyPopulated() {
User u = service.load(1L);
assertAll("user",
() -> assertEquals("harsh", u.getUsername()),
() -> assertEquals("harsh@example.com", u.getEmail()),
() -> assertTrue(u.isActive()));
}
AssertJ (bundled with the test starter) reads better for complex checks:
assertThat(products)
.hasSize(3)
.extracting(Product::getName)
.containsExactly("Pen", "Book", "Lamp");
Lifecycle Annotations
class OrderServiceTest {
@BeforeAll
static void bootOnce() { } // once, before any test — must be static
@BeforeEach
void freshState() { } // before EVERY test
@Test
void something() { }
@AfterEach
void cleanUp() { } // after EVERY test
@AfterAll
static void shutDown() { } // once, at the end
}
JUnit 5 creates a new instance of the test class for every test method. That is deliberate: it stops one test from leaking state into the next.
Parameterised Tests
One test method, many inputs:
@ParameterizedTest
@ValueSource(strings = {"", " ", " "})
void blankNamesAreRejected(String name) {
assertThrows(IllegalArgumentException.class, () -> new User(name));
}
@ParameterizedTest
@CsvSource({"1,1,2", "5,5,10", "-3,3,0"})
void addsCorrectly(int a, int b, int expected) {
assertEquals(expected, calc.add(a, b));
}
Three cases, one method, and the report names each one separately.
Common Mistakes
- Arguments reversed: The signature is
assertEquals(expected, actual). Swapping them makes every failure message misleading. assertTrue(a.equals(b)): Reports only "expected true, was false".assertEquals(a, b)prints both values.- Shared mutable state in
@BeforeAll: Tests then depend on execution order and fail randomly. - A test with no assertion: It passes as long as nothing throws — which proves almost nothing.
Best Practices
- One logical assertion per test, or
assertAllwhen the checks belong together. - Name tests as sentences:
withdrawFailsWhenBalanceTooLowbeatstest3. - Set up in
@BeforeEach, not@BeforeAll, unless the resource is genuinely expensive and immutable. - Prefer
@ParameterizedTestover copy-pasting a test five times.
Practice Exercises
- The Message Check: Use
assertThrowsand assert on the exception message, not just the type. - The Lifecycle Log: Print from all four lifecycle hooks with two
@Testmethods present, and record the exact order. - The Table: Convert four near-identical tests into one
@CsvSourceparameterised test.