java / beginner
Snippet
Simulating HTTP GET Requests with MockMvc
MockMvc enables fast and isolated testing of Spring MVC controllers without starting a full HTTP server. You can simulate requests and verify status codes, headers, and JSON responses declaratively.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
@WebMvcTest(UserController.class)class UserControllerTest {@Autowiredprivate MockMvc mockMvc;@Testvoid shouldReturnOkForUserEndpoint() throws Exception {mockMvc.perform(get("/users/1")).andExpect(status().isOk()).andExpect(jsonPath("$.name").value("Alice"));}}
spring
Breakdown
1
@WebMvcTest(UserController.class)
Instantiates only the web layer components needed to test the specified controller.
2
@Autowired private MockMvc mockMvc;
Injects the MockMvc helper provided by the Spring test framework.
3
mockMvc.perform(get("/users/1"))
Simulates a HTTP GET request to the /users/1 route.
4
.andExpect(status().isOk())
Asserts that the HTTP response code is 200 OK.
5
.andExpect(jsonPath("$.name").value("Alice"));
Inspects the JSON response body using JsonPath to verify the name field.