Testing
The starter
spring-boot-starter-test is in every generated project and brings JUnit 5, AssertJ,
Mockito, JSONassert and the Spring test support.
Plain unit tests
Constructor injection means most classes need no Spring at all.
Fast, and where the bulk of your tests should live.
Slice tests
Start only the part of the context you need.
| Annotation | Loads |
|---|---|
@WebMvcTest | controllers, JSON mapping, no services |
@DataJpaTest | JPA, repositories, in-memory database |
@RestClientTest | HTTP clients with a mock server |
@JsonTest | serialization only |
New in Spring Boot 4
RestTestClient is the one fluent test client for both mock and running servers.
@MockBean is gone — use @MockitoBean (and @MockitoSpyBean).
Repository tests
Each test runs in a transaction that is rolled back afterwards.
Full integration tests
Slow — a handful of these is enough.
Test configuration
src/test/resources/application.properties overrides settings during tests:
Or use a profile: @ActiveProfiles("test").
A real database with Testcontainers
@ServiceConnection wires the container’s URL, user and password into the context — no
property files.
What to test
- services: business rules, plain unit tests
- controllers: status codes, validation, JSON shape —
@WebMvcTest - repositories: custom queries only —
@DataJpaTest - end to end: one or two happy paths —
@SpringBootTest
Warning
A test that starts the whole context to check a string comparison costs seconds every run. Push tests down the pyramid.
★ Exercises
- Unit-test a service with no Spring annotations.
- Write a
@WebMvcTestwith@MockitoBeanfor the service. - Assert that an invalid POST body returns 400 and names the bad field.
- Write a
@DataJpaTestfor a derived query method. - Add one
@SpringBootTestcovering create-then-read.