The Test Pyramid in Spring Boot: Unit, Slice and Whole-App Tests
One small ticket desk, three kinds of test: four plain unit tests in 20 ms, two @WebMvcTest slice tests in 4.4 s, one @SpringBootTest flow in 711 ms. Where each rule belongs, and what you should never test at all.
What you will learn
- Write a plain unit test with no Spring for business rules and edges
- Test only the web layer with @WebMvcTest and a @MockitoBean stand-in
- Test the wiring with @SpringBootTest and @AutoConfigureMockMvc
- Decide what to unit test, what to integrate and what never to test
Before you start
- A Spring Boot REST API
- JUnit basics
When you write tests for an application, three questions come up fast. What should you unit test? What should you test with the pieces wired together? And what should you never test at all? Get the answers right and the whole suite stays fast enough that you'd happily run it every time you save a file.
Our example is a small ticket desk: a Spring Boot app where people open and close support tickets. We test it at three levels and time each one.
Level 1: unit tests, no Spring
class TicketServiceTest {
private final TicketService service = new TicketService(new TicketStore());
@Test
void ticketOpenForADayBecomesMedium() {
Ticket ticket = new Ticket(1, "Reset my password", Priority.LOW, 24, true);
assertEquals(Priority.MEDIUM, service.priority(ticket));
}
@Test
void ticketOpenForTwoDaysBecomesHigh() {
Ticket ticket = new Ticket(2, "VPN is down", Priority.LOW, 48, true);
assertEquals(Priority.HIGH, service.priority(ticket));
}
@Test
void freshTicketKeepsItsPriority() {
Ticket ticket = new Ticket(3, "Need a new mouse", Priority.LOW, 23, true);
assertEquals(Priority.LOW, service.priority(ticket));
}
@Test
void closingAnUnknownTicketFails() {
assertThrows(NoSuchElementException.class, () -> service.close(99));
}
}
Tests run: 4, Failures: 0
freshTicketKeepsItsPriority 7 ms
ticketOpenForTwoDaysBecomesHigh 1 ms
closingAnUnknownTicketFails 3 ms
ticketOpenForADayBecomesMedium 1 ms
The service is a plain object, built in one line with new. No server, no database, no Spring. Each test checks one rule: 24 hours open becomes MEDIUM, 48 hours becomes HIGH, 23 hours stays LOW (the edge right before the rule), and closing an unknown ticket fails. Four tests in 20 ms.
Level 2: a slice test, only the web layer
@WebMvcTest(TicketController.class)
class TicketControllerTest {
@Autowired
MockMvc mvc;
@MockitoBean
TicketService service;
@Test
void openingATicketReturns201() throws Exception {
given(service.open("Printer is jammed"))
.willReturn(new Ticket(1, "Printer is jammed", Priority.LOW, 0, true));
mvc.perform(post("/tickets").param("title", "Printer is jammed"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.title").value("Printer is jammed"));
}
@Test
void anUnknownTicketReturns404() throws Exception {
given(service.find(99)).willThrow(new NoSuchElementException());
mvc.perform(get("/tickets/99")).andExpect(status().isNotFound());
}
}
Tests run: 2, Failures: 0
anUnknownTicketReturns404 223 ms
openingATicketReturns201 164 ms
@WebMvcTest starts only the web layer of Spring: the controller and its JSON, not the whole application. @MockitoBean puts a stand-in in place of the real service, and given(...).willReturn(...) says what it answers. So the controller alone is under test: status codes, request parameters, JSON. The class took 4.4 s; most of that is starting part of Spring, not the tests.
Level 3: the whole app, wired together
@SpringBootTest
@AutoConfigureMockMvc
class TicketDeskFlowTest {
@Autowired
MockMvc mvc;
@Test
void openCloseAndReadATicket() throws Exception {
mvc.perform(post("/tickets").param("title", "VPN is down"))
.andExpect(status().isCreated());
mvc.perform(put("/tickets/1/close")).andExpect(status().isOk());
mvc.perform(get("/tickets/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.open").value(false));
}
}
Tests run: 1, Failures: 0
openCloseAndReadATicket 20 ms
@SpringBootTest starts the whole application: controller, service and store are all real, nothing mocked. @AutoConfigureMockMvc sends the requests straight in, without opening a network port. Open, close, read back, and open is now false. This one test checks that the pieces fit. The class took 711 ms.
Many fast tests, few slow ones
Why is the whole-app test faster than the slice here? Our ticket desk is tiny, so the whole application is barely bigger than one slice. In a real app with a database, messaging and hundreds of beans, the whole-app test is the one that gets slow. So the exact numbers don't matter much; the pattern does.
Unit, integrate, or never
| Unit test | Integration test | Never test |
|---|---|---|
| rules and decisions (24 h is MEDIUM, 23 h is not) | the wiring between controller, service and store | getters and records (ticket.title() returns the title) |
| edges and failures (unknown ticket must fail) | the API contract (201 on create, 404 when unknown) | what the framework already guarantees |
plain classes built with new | one happy path end to end | the language itself |
The rule of thumb: test each rule at the lowest level that can see it, and keep the top small. A priority rule tested through HTTP costs seconds and fails for ten unrelated reasons. Tested on the plain service, it costs one millisecond and fails for one.
Common mistakes
@SpringBootTeston every test class. Each one pays for starting Spring. Most rules need no Spring at all.- Only happy paths. The edge (23 hours) and the failure (ticket 99) are where bugs live.
- Testing getters to raise coverage. It adds run time and proves nothing.
- Business rules inside the controller. Then they can only be tested slowly. Keep them in the service.
Try it yourself
Add a rule: a ticket open for 72 hours or more becomes URGENT. Which level do you test it at, and which two hour values make the best pair of tests?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Unit Tests With AI for a Spring Boot Service: Mockito Mocks, Given-When-Then and a Green Run
CommentServiceTest runs the real CommentService with three Mockito mocks for its repositories: no Spring, no database, five tests in a fraction of a second. An AI drafts it from a short prompt; we read each test, run it, and learn to read the red message when an expectation is wrong.
Docker for a Spring Boot App: Run the Tests in the Image Build, or Skip Them on Purpose
The blog's Dockerfile runs mvnw package with -DskipTests=${SKIP_TESTS}, false by default, so every docker build runs all 53 tests and a red one means no image. --build-arg SKIP_TESTS=true cuts the package step from 41 to 23 seconds, which is only safe after CI has run the tests.
Mockito and Test Doubles: Stubs, Mocks and Fakes for One Java Class
Test TicketService.close on its own: a stub repository that answers findById, a mock notifier that records send, verify to check both calls, and a HashMap fake that really stores the closed ticket.
Spring Boot Test Slices: @WebMvcTest with MockMvc and @DataJpaTest
Start only the layer you test. Three MockMvc tests for a ticket controller (200 with JSON, 404, a JSON list), the 'no qualifying bean' failure when the mock is missing, two @DataJpaTest tests on H2, and bean counts of 124, 80 and 224.
