使用 @WebMvcTest 与 MockMvc 测试 Web 层
使用 @WebMvcTest 和 MockMvc 隔离测试 Spring Boot 控制器,而无需启动完整的应用上下文。
使用 @WebMvcTest 与 MockMvc 测试 Web 层 是 CoddyKit 上的免费 Testing Mastery: JUnit, Mockito & Integration Tests 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Testing Mastery: JUnit, Mockito & Integration Tests 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Testing Mastery: JUnit, Mockito & Integration Tests 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Slice Tests?
Loading the entire Spring context for every controller test is slow. Spring Boot offers test slices that load only the beans you need. @WebMvcTest loads just the web layer.
What @WebMvcTest Loads
@WebMvcTest configures controllers, filters, and JSON converters, but not services or repositories. Those collaborators are supplied as mocks.
Declaring the Test
Target a single controller so the slice stays small and fast.
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mockMvc;
}Mocking the Service
The controller's service dependency is replaced with a Mockito mock using @MockBean, which places the mock in the context.
@MockBean
UserService userService;Performing a Request
MockMvc simulates HTTP requests against your controller without a running server.
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());Stubbing Then Asserting
Stub the mocked service, fire the request, and assert on the response body and status.
when(userService.find(1L))
.thenReturn(new User(1L, "Ada"));
mockMvc.perform(get("/users/1"))
.andExpect(jsonPath("$.name").value("Ada"));Checking Status Codes
Validate error mappings, such as a 404 when the service signals a missing entity.
when(userService.find(9L))
.thenThrow(new NotFoundException());
mockMvc.perform(get("/users/9"))
.andExpect(status().isNotFound());Testing POST with a Body
Send JSON content and verify the controller deserializes and responds correctly.
mockMvc.perform(post("/users")
.contentType("application/json")
.content("{\"name\":\"Ada\"}"))
.andExpect(status().isCreated());JsonPath Assertions
jsonPath expressions let you assert on nested fields, array sizes, and values inside the JSON response.
.andExpect(jsonPath("$.items.length()").value(3))Slice vs Full Context
Use @WebMvcTest for focused, fast web-layer tests. Reserve @SpringBootTest for true end-to-end flows where you want the whole context wired.
Speed Benefits
Because only the web layer loads, these tests start in a fraction of the time of a full-context test, encouraging more thorough controller coverage.
Quick Check
How are service dependencies handled in a @WebMvcTest?
Recap
You learned web-layer slice testing:
@WebMvcTestloads only controllers and web infrastructureMockMvcsimulates HTTP requests without a server@MockBeansupplies mocked services- Assert status and body with
jsonPath
常见问题解答
「使用 @WebMvcTest 与 MockMvc 测试 Web 层」课时是免费的吗?
是的 — 「使用 @WebMvcTest 与 MockMvc 测试 Web 层」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Testing Mastery: JUnit, Mockito & Integration Tests 课程的其余内容,请升级到 CoddyKit PRO。 Testing Mastery: JUnit, Mockito & Integration Tests 课程共包含 4 节课。
「使用 @WebMvcTest 与 MockMvc 测试 Web 层」这节课中我会学到什么?
使用 @WebMvcTest 和 MockMvc 隔离测试 Spring Boot 控制器,而无需启动完整的应用上下文。 你通过在浏览器中直接运行的动手代码来练习 Testing Mastery: JUnit, Mockito & Integration Tests,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Testing Mastery: JUnit, Mockito & Integration Tests 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Testing Mastery: JUnit, Mockito & Integration Tests 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「使用 @WebMvcTest 与 MockMvc 测试 Web 层」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Testing Mastery: JUnit, Mockito & Integration Tests 课中编写并运行代码吗?
能。每节 Testing Mastery: JUnit, Mockito & Integration Tests 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- Spring 测试上下文框架
- 测试 RESTful API
- 用于测试的嵌入式数据库
- 使用 @WebMvcTest 与 MockMvc 测试 Web 层