Skip to content

Lesson 4 of 9 · 23m

Testing Slices That Test the Right Layer

Choose plain unit tests, MVC slices, data slices, and full context tests deliberately instead of paying Spring startup cost everywhere.

Test suites rot in a predictable way. The first tests are fast and useful. Then someone uses @SpringBootTest for everything because it is easy, the suite takes forty minutes, developers stop running it locally, and failures become background noise. The fix is not more discipline. It is choosing the right test boundary for the behavior being proven.

Unit tests prove decision logic

Plain JUnit tests should cover business rules, state transitions, validation policy, and edge cases:

class RefundPolicyTest {
    private final Clock clock = Clock.fixed(Instant.parse("2026-03-01T12:00:00Z"), ZoneOffset.UTC);
    private final RefundPolicy policy = new RefundPolicy(clock);

    @Test
    void rejectsRefundAfterThirtyDays() {
        var purchase = new Purchase(Instant.parse("2026-01-28T12:00:00Z"));
        assertThat(policy.canRefund(purchase)).isFalse();
    }
}

Web slices prove HTTP contracts

@WebMvcTest starts web infrastructure with selected controllers. It is appropriate for request mapping, validation, content negotiation, exception translation, and security behavior — not SQL, transaction isolation, or queue behavior:

@WebMvcTest(OrderController.class)
class OrderControllerTest {
    @Autowired MockMvc mvc;
    @MockBean OrderService orders;

    @Test
    void missingOrderBecomes404() throws Exception {
        given(orders.receipt(any())).willThrow(new OrderNotFound(UUID.randomUUID()));
        mvc.perform(get("/orders/{id}", UUID.randomUUID()))
            .andExpect(status().isNotFound());
    }
}

Data slices prove mapping and queries

@DataJpaTest validates entity mappings, custom queries, constraints, and projections against a real database boundary. If your production database is PostgreSQL, prefer Testcontainers PostgreSQL over an in-memory database with different semantics:

@DataJpaTest
@Testcontainers
class OrderRepositoryTest {
    @Container @ServiceConnection
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine");
}

A query can pass H2 and fail PostgreSQL because of types, operators, or locking behavior.

Field notes

  • @MockBean is now legacy in current Spring Boot lines; prefer @MockitoBean where available and follow the version's guidance.
  • Do not mock what you do not own. Use a fake or contract test for external clients instead of reproducing the HTTP library in Mockito.
  • A test that only asserts a mock was called proves wiring, not behavior.
  • Slices can disagree with production if configuration differs. Keep test configuration minimal and explicit.
  • Flaky tests are operational defects. Quarantine them only with an owner and expiry date, or they become permanent lies.

Was this lesson helpful?

Sign in to rate