0 day streak
java / intermediate
Snippet

Testing Controllers with MockMvc

MockMvc allows you to test Spring MVC controllers without starting a full HTTP server. It provides a DSL for performing requests and verifying results.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void shouldReturnUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("John"));
}
}
spring
Breakdown
1
@WebMvcTest(UserController.class)
Focuses the test only on the web layer, ignoring other beans.
2
.andExpect(status().isOk())
Verifies that the HTTP response code is 200 (OK).