0 day streak
java / intermediate
Snippet

Integration Testing with MockMvc

MockMvc provides a way to test the web layer without starting a full HTTP server. It allows you to simulate requests and verify responses, including status codes, JSON content, and headers.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void shouldReturnUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.username").value("john_doe"))
.andExpect(header().exists("Content-Type"));
}
}
spring
Breakdown
1
@AutoConfigureMockMvc
Configures the MockMvc instance for use in the test class.
2
mockMvc.perform(get(...))
Simulates an HTTP GET request to the specified endpoint.
3
jsonPath("$.username")
An expression used to inspect the JSON body of the response.