Spring Boot: From Basics to Production · Testing Spring Boot Applications
Web Layer Tests with @WebMvcTest and MockMvc
Test controllers, validation, JSON and security without the full app.
@WebMvcTest(ProductController.class) starts only the MVC slice (controllers, advice, JSON, security filters) and provides MockMvc (or MockMvcTester with AssertJ). Mock services with @MockitoBean (replacing the deprecated @MockBean). Test status codes, JSON bodies, validation errors and authorization rules (spring-security-test adds jwt() and @WithMockUser).
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired MockMvc mvc;
@MockitoBean ProductService products;
@Test
void returns404ProblemDetailForUnknownProduct() throws Exception {
when(products.get(42)).thenThrow(new NotFoundException("Product 42 not found"));
mvc.perform(get("/api/v1/products/42"))
.andExpect(status().isNotFound())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.detail").value("Product 42 not found"));
}
@Test
void rejectsInvalidCreateRequest() throws Exception {
mvc.perform(post("/api/v1/products").with(jwt().authorities(new SimpleGrantedAuthority("ROLE_ADMIN")))
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\": \"\", \"priceCents\": -1, \"currency\": \"USD\"}"))
.andExpect(status().isBadRequest());
}
}
Common pitfalls
- Loading the full context when only the web layer matters.
- Not testing security rules (unauthenticated → 401, wrong role → 403).
- Asserting on whole JSON strings that break on field order.
Key points
- @WebMvcTest loads only MVC
- @MockitoBean for service mocks
- Test validation, errors and security
Further reading: Spring Boot: Spring MVC tests
Practice questions
What does @WebMvcTest include and exclude?
Answer
It includes controllers, controller advice, converters, filters and security configuration, but not services, repositories or the database — those must be mocked.
What replaced @MockBean in recent Spring versions?
Answer
@MockitoBean (and @MockitoSpyBean) from Spring Framework 6.2; @MockBean is deprecated since Spring Boot 3.4.
Open in the app to mark lessons complete, take notes and track your progress.