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.
What you will learn
- Test a controller alone with @WebMvcTest and MockMvc, checking status and JSON
- Replace the service with @MockitoBean and read the error when it is missing
- Test a repository alone with @DataJpaTest on in-memory H2
- Compare what each slice loads, by bean count
Before you start
- The Test Pyramid in Spring Boot
- Mockito and Test Doubles
With @SpringBootTest, Spring starts the whole app for a test: every layer, every bean. That's fine sometimes, but heavy for a test that only cares about one controller. A test slice starts one layer and leaves the rest out, or replaces it with a mock.
Our Ticket Desk has a controller, a service, a repository and an H2 database. We'll slice it twice.
The two test starters
The slices come from two test-scope dependencies in the pom: spring-boot-starter-webmvc-test (for @WebMvcTest, bringing MockMvc and JSON path support) and spring-boot-starter-data-jpa-test (for @DataJpaTest). H2 is already on the classpath, so @DataJpaTest swaps in an in-memory database by itself.
Slice 1: the controller alone
The controller under test is a @RestController on /tickets. It gets a TicketService through its constructor (remember that), returns one ticket by id or a 404 when the service gives back an empty Optional, and lists tickets by ?status=.
@WebMvcTest(TicketController.class)
class TicketControllerTest {
@Autowired
MockMvc mockMvc;
@MockitoBean
TicketService service;
@Test
void returnsOneTicket() throws Exception {
given(service.find(1L))
.willReturn(Optional.of(new Ticket(1L, "Printer jammed", Status.OPEN)));
mockMvc.perform(get("/tickets/1"))
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Printer jammed"))
.andExpect(jsonPath("$.status").value("OPEN"));
}
@Test
void unknownTicketIs404() throws Exception {
given(service.find(99L)).willReturn(Optional.empty());
mockMvc.perform(get("/tickets/99"))
.andExpect(status().isNotFound());
}
@Test
void listsOpenTickets() throws Exception {
given(service.findByStatus(Status.OPEN)).willReturn(List.of(
new Ticket(1L, "Printer jammed", Status.OPEN),
new Ticket(2L, "Wi-Fi is slow", Status.OPEN)));
mockMvc.perform(get("/tickets").param("status", "OPEN"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(2))
.andExpect(jsonPath("$[1].title").value("Wi-Fi is slow"));
}
}
All three tests pass. @WebMvcTest(TicketController.class) loads the web layer for that one controller. MockMvc calls it without starting any server: perform(get("/tickets/1")) goes through Spring MVC's DispatcherServlet straight to the controller, the controller asks the mock, and the JSON comes back to the test. jsonPath("$.title") reads one field, $.length() counts a list, $[1].title reads the second item. .andDo(print()) prints the whole request and response, which helps when a test fails.
Break it: leave out the mock
Turn the @MockitoBean field into a plain field and rerun. All three tests fail:
Failed to load ApplicationContext for TicketControllerTest
...
No qualifying bean of type 'TicketService'
The controller's constructor asks for a TicketService, and a web slice doesn't load services at all. There's a hole, and Spring can't build the controller. In a slice, every collaborator outside the layer needs a @MockitoBean.
Slice 2: the repository alone
@DataJpaTest
class TicketRepositoryTest {
@Autowired
TicketRepository repository;
@Test
void findsOnlyOpenTickets() {
repository.save(new Ticket("Printer jammed", Status.OPEN));
repository.save(new Ticket("Password reset", Status.CLOSED));
repository.save(new Ticket("Wi-Fi is slow", Status.OPEN));
List<Ticket> open = repository.findByStatus(Status.OPEN);
assertThat(open).extracting(Ticket::getTitle)
.containsExactlyInAnyOrder("Printer jammed", "Wi-Fi is slow");
}
@Test
void savingGivesAnId() {
Ticket saved = repository.save(new Ticket("Printer jammed", Status.OPEN));
assertThat(saved.getId()).isNotNull();
}
}
Both pass. @DataJpaTest loads entities, repositories and an in-memory H2 database. Here the repository is real: no controller, no service, no mock. We save three tickets, two open and one closed, and the query under test must return exactly the two open ones. That checks the derived query findByStatus against a real database engine, which a mock never could.
Common mistakes
- Forgetting the
@MockitoBean. "No qualifying bean" in a web slice nearly always means this. - Mocking the repository in a
@DataJpaTest. The point is to run the real query. - Trusting H2 for PostgreSQL-only SQL. A native query or a Postgres feature can pass on H2 and fail in production. That's what Testcontainers is for (see Integration Tests with Testcontainers).
@WebMvcTestwithout a controller class. It then loads every controller, and you need mocks for all of their services.
Recap
| Annotation | Loads | Checks |
|---|---|---|
@WebMvcTest(X.class) | one controller, MVC, MockMvc | status, JSON, request mapping |
@MockitoBean | a mock in place of a missing bean | what the controller sees |
@DataJpaTest | JPA, repositories, in-memory H2 | real queries |
@SpringBootTest | almost everything | the wiring |
Try it yourself
Add a test to TicketControllerTest for GET /tickets?status=CLOSED where the mock returns an empty list. What should jsonPath("$.length()") be, and what status do you expect?
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.
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.
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.
