使用 MockMvc 测试 Web 控制器
使用 MockMvc 模拟 HTTP 请求,无需启动真实服务器即可为 REST 端点编写针对性测试。
使用 MockMvc 测试 Web 控制器 是 CoddyKit 上的免费 Spring Boot 4 Complete Guide 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Complete Guide 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Complete Guide 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Test Controllers in Isolation?
Controller tests verify routing, request mapping, status codes, and JSON serialization without the cost of a full server. MockMvc makes this fast and precise.
Introducing @WebMvcTest
The @WebMvcTest annotation loads only the web layer, your controllers and their supporting beans, keeping the test slice small and quick.
@WebMvcTest(UserController.class)
class UserControllerTest {
}Injecting MockMvc
Inside a @WebMvcTest, Spring provides an auto-configured MockMvc instance you autowire to perform simulated requests.
@Autowired
MockMvc mockMvc;Performing a GET Request
Use the fluent API to perform a request and chain expectations on the response.
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());Mocking the Service Layer
Controllers depend on services, so you replace them with mocks using @MockBean. This isolates the controller from real business logic.
@MockBean
UserService userService;Stubbing Behavior
Combine Mockito stubbing with the request to control what the service returns.
when(userService.find(1L)).thenReturn(new User("Ada"));Asserting JSON Content
Use jsonPath to verify specific fields in the response body.
mockMvc.perform(get("/users/1"))
.andExpect(jsonPath("$.name").value("Ada"));Testing POST with a Body
Send a JSON payload and assert the created status, verifying your endpoint accepts and processes input correctly.
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Ada\"}"))
.andExpect(status().isCreated());Verifying Validation Errors
Send invalid input and assert a 400 Bad Request to confirm your validation rules actually fire.
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isBadRequest());Verifying Interactions
Use Mockito's verify to confirm the controller actually called the service the expected number of times.
verify(userService).find(1L);When to Use Full Integration Tests
MockMvc slice tests are fast but mock the service. For end-to-end confidence across the real stack, complement them with full @SpringBootTest integration tests.
Quick Check
Test your understanding of MockMvc controller testing.
Recap
You used @WebMvcTest with MockMvc to test endpoints, mocked services with @MockBean, and asserted status codes and JSON. These slice tests are a fast first line of defense.
常见问题解答
「使用 MockMvc 测试 Web 控制器」课时是免费的吗?
是的 — 「使用 MockMvc 测试 Web 控制器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Complete Guide 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Complete Guide 课程共包含 4 节课。
「使用 MockMvc 测试 Web 控制器」这节课中我会学到什么?
使用 MockMvc 模拟 HTTP 请求,无需启动真实服务器即可为 REST 端点编写针对性测试。 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Complete Guide,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Spring Boot 4 Complete Guide 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Spring Boot 4 Complete Guide 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「使用 MockMvc 测试 Web 控制器」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Spring Boot 4 Complete Guide 课中编写并运行代码吗?
能。每节 Spring Boot 4 Complete Guide 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 JUnit 与 Mockito 进行单元测试
- 使用 Spring Boot 进行集成测试
- 切片测试与 TestContainers
- 使用 MockMvc 测试 Web 控制器