Skip to content

MockMvc Testing Framework

MockMvc is a testing framework provided by Spring MVC that allows developers to perform integration testing for the controller layer without starting a full HTTP server^[600-developer__java__spring__spring-note.md]. It operates by making requests to the DispatcherServlet through a mock mechanism^[600-developer__java__spring__spring-note.md], enabling the verification of MVC behaviors such as request mappings, input validation, and response handling within a Spring application context^[600-developer__java__spring__spring-note.md].

Setup and Configuration

To utilize MockMvc in a test, the instance must be built, typically using the MockMvcBuilders class^[600-developer__java__spring__spring-note.md]. The standard approach for integration tests involves loading the full WebApplicationContext and using it to configure the MockMvc instance^[600-developer__java__spring__spring-note.md].

Initialization Example

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Before
public void setup() {
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
^[600-developer__java__spring__spring-note.md]

Usage

Tests are executed by calling perform() on the MockMvc instance, passing in a request builder method (e.g., delete, get, post) that defines the HTTP method and endpoint^[600-developer__java__spring__spring-note.md]. The result is validated using andExpect() to check specific response conditions, such as the HTTP status code^[600-developer__java__spring__spring-note.md].

Test Execution Example

In the following example, a DELETE request is performed against the /user/1 endpoint, expecting a successful 200 OK response^[600-developer__java__spring__spring-note.md]:

@Test
public void whenDeleteSuccess() throws Exception {
    mockMvc.perform(delete("/user/1")
            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk());
}
^[600-developer__java__spring__spring-note.md]

  • [[Spring MVC]]
  • [[Integration Testing]]

Sources

  • 600-developer__java__spring__spring-note.md