0 day streak
java / beginner
Snippet

Verifying REST Endpoints with MockMvc Assertions

MockMvc enables fast and isolated testing of Spring MVC controller endpoints without spinning up a full HTTP web server, allowing developers to assert HTTP status codes and responses directly.

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 shouldReturnOkStatus() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk());
}
}
spring
Breakdown
1
@WebMvcTest(UserController.class)
Bootstraps a slice of the Spring ApplicationContext focusing solely on Spring MVC components for UserController.
2
private MockMvc mockMvc;
Injects the main entry point for server-side Spring MVC testing support.
3
mockMvc.perform(get("/api/users/1"))
Constructs and executes a simulated HTTP GET request to the specified endpoint path.
4
.andExpect(status().isOk());
Asserts that the simulated response status matches HTTP 200 OK.