Lesson 22 / 38

JUnit 5 & Mockito

Write unit tests with JUnit 5 assertions and parameterized tests, and isolate a class under test by stubbing its collaborators with Mockito.

A JUnit 5 test

@Test methods use Assertions.assertEquals, assertThrows, assertAll. @ParameterizedTest runs one body over many inputs. Mockito creates stub collaborators so you test one unit in isolation.

@Test
void appliesDiscount() {
    PriceService svc = new PriceService(rules);
    assertEquals(90, svc.total(100, "SAVE10"));
}

@Test
void rejectsUnknownCode() {
    when(rules.lookup("X")).thenReturn(Optional.empty());
    assertThrows(BadCode.class, () -> svc.total(100, "X"));
}

Test design check

Quick check: Why replace a real database call with a mock in a unit test?

  • Mocks are always more accurate than the real thing
  • To keep the test fast, deterministic, and focused on one unit
  • Because JUnit cannot call external code
  • To avoid writing assertions
Answer

To keep the test fast, deterministic, and focused on one unit — Integration tests still exercise the real DB; unit tests isolate logic so failures point to one place.