How to Use MockMvc in Spring Boot for Controller Testing
Use
MockMvc in Spring Boot to test your web controllers by simulating HTTP requests and verifying responses without starting a server. You create a MockMvc instance with @AutoConfigureMockMvc and inject it in your test class, then perform requests and assert results using its fluent API.Syntax
The basic syntax to use MockMvc involves creating a test class annotated with @SpringBootTest and @AutoConfigureMockMvc. Inject MockMvc with @Autowired. Use mockMvc.perform() to simulate HTTP requests, then chain andExpect() calls to check the response.
@SpringBootTest: Loads the full application context.@AutoConfigureMockMvc: ConfiguresMockMvcfor testing.mockMvc.perform(): Executes a request like GET or POST.andExpect(): Verifies status, content, headers, etc.
java
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.web.servlet.MockMvc; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @AutoConfigureMockMvc public class MyControllerTest { @Autowired private MockMvc mockMvc; @org.junit.jupiter.api.Test public void testExample() throws Exception { mockMvc.perform(get("/example")) .andExpect(status().isOk()); } }
Example
This example shows a simple Spring Boot controller test using MockMvc. It tests a GET request to /hello and expects a 200 OK status with the response body Hello, World!.
java
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.web.servlet.MockMvc; import org.junit.jupiter.api.Test; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootTest @AutoConfigureMockMvc public class HelloControllerTest { @Autowired private MockMvc mockMvc; @RestController static class HelloController { @GetMapping("/hello") public String hello() { return "Hello, World!"; } } @Test public void helloEndpointReturnsHelloWorld() throws Exception { mockMvc.perform(get("/hello")) .andExpect(status().isOk()) .andExpect(content().string("Hello, World!")); } }
Output
Test passed: GET /hello returns 200 OK with body "Hello, World!"
Common Pitfalls
- Not annotating the test class with
@AutoConfigureMockMvccausesMockMvcnot to be injected. - Forgetting
@SpringBootTestmeans the application context is not loaded, so controllers are missing. - Using
mockMvc.perform()without proper imports for request builders and result matchers leads to compilation errors. - Testing endpoints that require authentication without mocking security causes 401 errors.
java
/* Wrong: Missing @AutoConfigureMockMvc, mockMvc will be null */ @SpringBootTest public class WrongTest { @Autowired private MockMvc mockMvc; // null, test fails } /* Right: Add @AutoConfigureMockMvc to enable MockMvc injection */ @SpringBootTest @AutoConfigureMockMvc public class RightTest { @Autowired private MockMvc mockMvc; // properly injected }
Quick Reference
Here is a quick cheat sheet for common MockMvc usage:
| Action | Code Example | Description |
|---|---|---|
| Perform GET request | mockMvc.perform(get("/path")) | Simulate a GET HTTP request to /path |
| Check status OK | .andExpect(status().isOk()) | Verify response status is 200 OK |
| Check response content | .andExpect(content().string("text")) | Verify response body matches text |
| Perform POST with JSON | mockMvc.perform(post("/path").content(json).contentType(MediaType.APPLICATION_JSON)) | Send POST request with JSON body |
| Check JSON field | .andExpect(jsonPath("$.field").value("value")) | Verify JSON response field value |
Key Takeaways
Annotate your test class with @SpringBootTest and @AutoConfigureMockMvc to enable MockMvc.
Inject MockMvc with @Autowired to simulate HTTP requests without starting a server.
Use mockMvc.perform() with request builders and chain andExpect() to verify responses.
Remember to import static methods for request builders and result matchers for cleaner code.
MockMvc tests are fast and isolate controller logic, ideal for unit and integration testing.