---
title: "Testing Spring applications"
chapter: "09"
---

# Testing Spring applications

Use the smallest test that proves the behavior.

## Test pyramid

- Plain unit test: business class with fakes or mocks; no Spring context.
- Slice test: one layer such as MVC or JPA with focused configuration.
- Integration test: multiple real components and infrastructure.
- Contract test: provider and consumer agree on messages or APIs.
- End-to-end test: a few critical journeys through the deployed system.

## Spring tools

`MockMvc` tests Spring MVC without a real server. `WebTestClient` tests WebFlux
and can also drive live HTTP. `@SpringBootTest` loads broad Boot context; use it
when that breadth is the subject, not as the default for every method.

Testcontainers can run real databases, brokers, and services in containers.
Prefer realistic infrastructure for SQL, migration, and serialization behavior
that an in-memory substitute can hide.

## Transactional tests

A test transaction that rolls back can hide production flush, commit, and
event behavior. Force flush or run true integration boundaries when those
details matter.

## Healthy test design

Assert public behavior, not internal call order. Keep fixtures readable and
deterministic. Test validation, authorization, failures, timeouts, and retries,
not only success.

## Feynman check

A unit test checks one gear. A slice test checks one machine section. An
integration test connects machines. An end-to-end test follows one real parcel
through the factory.
