Sub topic 14
Testing the web layer with MockMvc
This chapter adds automated tests for the BookController and ApiExceptionHandler you built earlier. It assumes you can read JUnit 5 tests, know the basics of Mockito (when, verify), and understand the controller, service, and validation code from the previous chapters.
What a web-layer slice test covers
A slice test starts only the part of the application that one layer needs. @WebMvcTest starts the Spring MVC infrastructure and nothing else. The test context contains:
- The controllers you name, such as
BookController @RestControllerAdviceclasses such asApiExceptionHandler- Jackson message converters, argument resolvers (including
Pageable), and validation - A
MockMvcobject that sends requests into that infrastructure
It does not contain @Service, @Repository, or @Component beans, and it does not start a database or a real HTTP server. The controller's dependency, BookService, must therefore be replaced by a mock.
This design makes the tests fast and focused. A failing test points at request mapping, JSON binding, validation, status codes, or error handling. It does not point at SQL or transactions.
| Annotation | Starts | Typical use |
|---|---|---|
| `@WebMvcTest` | MVC components, `MockMvc` | Mappings, JSON, validation, error responses |
| `@DataJpaTest` | JPA, repositories, embedded database | Queries and entity mapping |
| `@SpringBootTest` | The whole application | End-to-end behavior and wiring checks |
MockMvc calls the DispatcherServlet directly, with no network socket. Request mapping, content negotiation, JSON conversion, @Valid, and exception handlers all run for real.
Setting up the test class
spring-boot-starter-test, already in your pom.xml, brings JUnit 5, Mockito, AssertJ, JSONassert, JsonPath, and the Spring test support. You need nothing else.
package com.example.books;
import static org.hamcrest.Matchers.endsWith;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(BookController.class)
class BookControllerTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private BookService service;
@Test
void returnsBookById() throws Exception {
when(service.get(1L)).thenReturn(new BookResponse(1L, "Dune", "Frank Herbert"));
mockMvc.perform(get("/api/books/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.title").value("Dune"))
.andExpect(jsonPath("$.author").value("Frank Herbert"));
}
@Test
void returnsNotFoundAsProblemDetail() throws Exception {
when(service.get(1L)).thenThrow(new BookNotFoundException(1L));
mockMvc.perform(get("/api/books/1"))
.andExpect(status().isNotFound())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.title").value("Book not found"))
.andExpect(jsonPath("$.detail").value("Book 1 not found"))
.andExpect(jsonPath("$.status").value(404));
}
}The content() matcher in the second test needs one more static import, so add it to the import block:
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;Three points about this class:
@MockitoBeanregisters a Mockito mock as theBookServicebean in the Spring context and resets it after each test. It requires Spring Boot 3.4 or later. On older versions, use@MockBeanfromorg.springframework.boot.test.mock.mockito.mockMvc.perform(...)returns aResultActions. You chainandExpect(...)calls, and each one throws anAssertionErroron a mismatch.jsonPathuses [JsonPath](https://github.com/json-path/JsonPath) expressions.$is the root of the response body.
Testing each CRUD operation
Test each endpoint for its success status and for the failures that matter. Because the service is a mock, you decide what it returns and what it throws.
Create: 201, Location, and the body
@Test
void createReturns201WithLocationHeader() throws Exception {
when(service.create(any(BookRequest.class)))
.thenReturn(new BookResponse(7L, "Dune", "Frank Herbert"));
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"title":"Dune","author":"Frank Herbert"}
"""))
.andExpect(status().isCreated())
.andExpect(header().string("Location", endsWith("/api/books/7")))
.andExpect(jsonPath("$.id").value(7));
verify(service).create(new BookRequest("Dune", "Frank Herbert"));
}The verify line checks that Jackson bound the JSON to the BookRequest you expect. Records implement equals, so the comparison works with no extra code. The location is http://localhost/api/books/7 in tests, so match only the end of it.
Java text blocks (""") avoid the escaped quotes in the version shown in the spine. They need Java 15 or later, and Spring Boot 3 already requires Java 17.
Read a page
@Test
void listReturnsPage() throws Exception {
when(service.list(any(Pageable.class)))
.thenReturn(new PageImpl<>(List.of(new BookResponse(1L, "Dune", "Frank Herbert"))));
mockMvc.perform(get("/api/books").param("page", "0").param("size", "5").param("sort", "title,asc"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content[0].title").value("Dune"))
.andExpect(jsonPath("$.totalElements").value(1));
}To check that the query parameters reach the service as a Pageable, capture the argument with Mockito's ArgumentCaptor<Pageable> and assert getPageSize() and getSort(). That confirms the page, size, and sort parameters are resolved as the controller expects.
Update and delete
@Test
void updateReturnsUpdatedBook() throws Exception {
when(service.update(any(Long.class), any(BookRequest.class)))
.thenReturn(new BookResponse(1L, "Dune Messiah", "Frank Herbert"));
mockMvc.perform(put("/api/books/1")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"Dune Messiah\",\"author\":\"Frank Herbert\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.title").value("Dune Messiah"));
}
@Test
void deleteReturns204() throws Exception {
mockMvc.perform(delete("/api/books/1"))
.andExpect(status().isNoContent());
verify(service).delete(1L);
}
@Test
void deleteOfUnknownBookReturns404() throws Exception {
doThrow(new BookNotFoundException(99L)).when(service).delete(99L);
mockMvc.perform(delete("/api/books/99"))
.andExpect(status().isNotFound());
}delete returns void, so you cannot use when(...) to make it throw. Use doThrow(...).when(service).delete(...) instead.
Testing validation failures
Validation runs in the web layer, before the service is called. Test that bad input produces a 400 and that the service is never reached.
@Test
void blankTitleIsRejectedBeforeReachingService() throws Exception {
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":\"\",\"author\":\"Ada\"}"))
.andExpect(status().isBadRequest());
verifyNoInteractions(service);
}
@Test
void malformedJsonIsRejected() throws Exception {
mockMvc.perform(post("/api/books")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"title\":"))
.andExpect(status().isBadRequest());
}
@Test
void missingContentTypeIsRejected() throws Exception {
mockMvc.perform(post("/api/books").content("{\"title\":\"Dune\",\"author\":\"Ada\"}"))
.andExpect(status().isUnsupportedMediaType());
}The first test covers @Valid with @NotBlank. The second covers a body that cannot be parsed. The third shows that without a Content-Type header Spring cannot pick a converter and answers 415. Tests that run into 415 by accident are a common source of confusion, so set contentType on every request that has a body.
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| `NoSuchBeanDefinitionException` for `BookService` | The service is not mocked, and `@WebMvcTest` does not scan `@Service` classes | Add `@MockitoBean BookService service` |
| 415 when you expected 200 or 201 | No `contentType(MediaType.APPLICATION_JSON)` | Set the content type on the request |
| 200 with an empty body | The mock was not stubbed, so it returned `null` | Stub the call with `when(...)` |
| `Status expected:<201> but was:<400>` | The request JSON fails validation or does not parse | Print the response with `.andDo(print())` |
| `JsonPath` error "No value at JSON path" | The path does not match the structure, for example `$.title` on a page | Use `$.content[0].title` for page responses |
| `UnsatisfiedDependencyException` mentioning a repository | Another bean in the context needs a repository, such as a component outside the controller | Mock it, or narrow the test with `@WebMvcTest(BookController.class)` |
Gotchas worth knowing
- Paged JSON shape. Serializing
PageImpldirectly works, but recent Spring Data versions log a warning that the JSON structure is not guaranteed to stay stable. If the page shape is part of your public contract, consider the DTO serialization mode that Spring Data offers, or return your own page record. - Security. If you later add Spring Security,
@WebMvcTestincludes its filter chain. Requests then return 401 or 403 until you addspring-security-testand usewith(user(...))or@WithMockUser, andwith(csrf())for state-changing requests. - Test naming and scope. Name tests by behavior, such as
deleteOfUnknownBookReturns404. Put one scenario in each test so a failure names the broken behavior. - Controller tests are not service tests. Business rules belong in plain unit tests of
BookServicewith a mocked repository, which need no Spring context at all.
Running the tests
Run the whole suite with Maven:
./mvnw testTo run only this class, add -Dtest=BookControllerTest. The slice context starts in a second or two and is cached between test classes that share the same configuration.
Exercise
A teammate writes a @WebMvcTest(BookController.class) test for POST /api/books and gets a 415 response. The controller and JSON are correct. What is the most likely cause, and how do you fix it?
Show answer
The request has no Content-Type header, so Spring cannot select a message converter for the body. Add .contentType(MediaType.APPLICATION_JSON) to the post(...) request builder.
Exercise
Why does the test for deleting an unknown book use doThrow(...).when(service).delete(99L) instead of when(service.delete(99L)).thenThrow(...)?
Show answer
delete returns void, and when(...) needs a value to wrap, so when(service.delete(99L)) does not compile. The doThrow(...).when(mock).method(...) form works for void methods.
Exercise
Write the assertion lines (after mockMvc.perform(...)) that check a validation failure on POST /api/books returns 400 and that BookService was never called.
Show answer
.andExpect(status().isBadRequest()); followed by verifyNoInteractions(service);. Validation runs before the controller method body, so the mocked service sees no calls.