java / intermediate
Snippet
Isolated Controller Validation Testing with @WebMvcTest
@WebMvcTest loads only the web layer without bootstrapping full service and repository context. In combination with MockMvc and @MockBean, it enables focused testing of HTTP status codes, payload serialization, and Jakarta Bean Validation constraints.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@WebMvcTest(UserController.class)class UserControllerTest {@Autowiredprivate MockMvc mockMvc;@MockBeanprivate UserService userService;@Testvoid whenInvalidEmail_thenReturnsUnprocessableEntity() throws Exception {String invalidPayload = "{\"email\": \"not-an-email\"}";mockMvc.perform(post("/api/users").contentType(MediaType.APPLICATION_JSON).content(invalidPayload)).andExpect(status().isUnprocessableEntity()).andExpect(jsonPath("$.errors[0].field").value("email"));}}
spring
Breakdown
1
@WebMvcTest(UserController.class)
Instantiates only the specified controller and underlying Spring MVC infrastructure components.
2
@MockBean private UserService userService;
Injects a Mockito mock into the application context to isolate the web layer from business logic.
3
mockMvc.perform(post("/api/users")...)
Simulates an incoming HTTP POST request with a JSON payload against the endpoint.
4
.andExpect(status().isUnprocessableEntity())
Asserts that the validation failure triggers an HTTP 422 response status.