MockMvc helps you test your web controllers without starting a real server. It lets you check HTTP requests and responses quickly and easily.
0
0
MockMvc for HTTP assertions in Spring Boot
Introduction
You want to test your Spring Boot controller methods without running the full application.
You need to verify that your API endpoints return the correct status and data.
You want to simulate HTTP requests like GET, POST, PUT, DELETE in tests.
You want fast feedback on your web layer logic during development.
You want to check JSON responses or headers from your controllers.
Syntax
Spring Boot
mockMvc.perform(requestBuilder)
.andExpect(status().isOk())
.andExpect(content().json(expectedJson))
.andReturn();mockMvc.perform() sends a fake HTTP request to your controller.
andExpect() checks the response status, content, or headers.
Examples
Test a GET request to '/api/hello' expecting status 200 and response body 'Hello World'.
Spring Boot
mockMvc.perform(get("/api/hello")) .andExpect(status().isOk()) .andExpect(content().string("Hello World"));
Test a POST request with JSON body to create a user, expecting status 201 Created.
Spring Boot
mockMvc.perform(post("/api/users") .contentType(MediaType.APPLICATION_JSON) .content("{\"name\":\"Alice\"}")) .andExpect(status().isCreated());
Test GET request for item with id 1, checking JSON fields using jsonPath.
Spring Boot
mockMvc.perform(get("/api/items/1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.id").value(1)) .andExpect(jsonPath("$.name").value("Item One"));
Sample Program
This test sends a GET request to '/hello' and checks that the response is 200 OK with the text 'Hello World'.
Spring Boot
import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; 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.*; @WebMvcTest(HelloController.class) public class HelloControllerTest { @Autowired private MockMvc mockMvc; @Test public void testHelloEndpoint() throws Exception { mockMvc.perform(get("/hello")) .andExpect(status().isOk()) .andExpect(content().string("Hello World")); } } // Controller for reference: // @RestController // public class HelloController { // @GetMapping("/hello") // public String hello() { // return "Hello World"; // } // }
OutputSuccess
Important Notes
MockMvc tests only the web layer, so other parts like database are not started unless mocked.
Use @WebMvcTest to load only controller-related beans for faster tests.
You can chain multiple andExpect() calls to check different parts of the response.
Summary
MockMvc lets you test Spring Boot controllers without a real server.
It simulates HTTP requests and checks responses easily.
Use it to verify status codes, response bodies, and headers in your tests.