Testing Spring Boot Applications¶
Choose the smallest test scope that can disprove the claim you care about.
| Scope | Question |
|---|---|
| Plain unit test | Does this object implement its contract? |
| MVC slice | Are routing, serialization, validation, and advice correct? |
| Persistence slice | Do mappings and queries behave against a database contract? |
| Full application context | Does configured application wiring collaborate? |
| End-to-end | Does the running system satisfy an external scenario? |
Unit first¶
Application and domain services with constructor dependencies can often be tested without Spring. This keeps tests fast and makes dependencies explicit.
Slices and full context¶
Spring Boot provides focused test slices and @SpringBootTest for a full
application context. A slice is not automatically a unit test; it starts a
restricted context to test one integration boundary. Do not load the full
context merely to call a pure method.
Real dependencies¶
An in-memory database can differ from the production database in SQL grammar, types, locking, constraints, and plans. Testcontainers can run a compatible real service for high-value integration tests. Keep schema migrations in the test path so the test validates the same evolution mechanism.
The cross-cutting testing-techniques guide compares test doubles, contract tests, property-based testing, nondeterminism, and mutation testing.
Transactional tests¶
Automatic rollback is convenient but can conceal flush, commit, locking, and lazy-loading behavior described in the lazy-versus-eager guide. Force a flush when the assertion concerns database constraints, and include committed-boundary tests for transaction behavior.
API tests¶
Assert status, headers, content type, body schema, and error contract. Security tests should cover unauthenticated, authenticated-but-forbidden, and allowed requests—not only the success path.
See the current Spring Boot testing reference and Testcontainers integration.