0 day streak
java / intermediate
Snippet

Validating Controller Request Payloads Using MockMvc and @WebMvcTest

`@WebMvcTest` narrows the Spring ApplicationContext down to the web layer, loading only controllers, converters, and validation logic rather than the full context. `MockMvc` provides a fluent DSL to simulate HTTP requests without starting an actual embedded web server, allowing fast verification of request body parsing, routing, and bean validation constraints.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void shouldRejectInvalidEmail() throws Exception {
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\": \"Anna\", \"email\": \"invalid-email\"}"))
.andExpect(status().isBadRequest());
}
}
spring
Breakdown
1
@WebMvcTest(UserController.class)
Configures a sliced Spring context focused solely on MVC components related to `UserController`.
2
mockMvc.perform(post("/users")
Initiates a mock HTTP POST request targeting the `/users` endpoint.
3
.andExpect(status().isBadRequest());
Asserts that the controller responds with HTTP 400 Bad Request due to validation failure on the email field.