Overview

您可以通过实例化控制器、注入依赖项并调用其方法来为 Spring MVC 编写纯单元测试。但是,此类测试不验证请求映射、数据绑定、消息转换、类型转换、验证,也不涉及任何支持的 @InitBinder@ModelAttribute@ExceptionHandler 方法。

You can write plain unit tests for Spring MVC by instantiating a controller, injecting it with dependencies, and calling its methods. However such tests do not verify request mappings, data binding, message conversion, type conversion, validation, and nor do they involve any of the supporting @InitBinder, @ModelAttribute, or @ExceptionHandler methods.

MockMvc 旨在为 Spring MVC controllers 提供更完整的测试,而无需正在运行的服务器。它通过调用 DispatcherServlet 和传递来自 spring-test 模块的 Servlet API 的 xref:testing/unit.adoc#mock-objects-servlet[“mock” 实现来实现这一点,该实现使用无正在运行的服务器的 Spring MVC 请求处理方式复制所有内容。

MockMvc aims to provide more complete testing for Spring MVC controllers without a running server. It does that by invoking the DispatcherServlet and passing “mock” implementations of the Servlet API from the spring-test module which replicates the full Spring MVC request handling without a running server.

MockMvc 是一个服务器端测试框架,它允许您使用轻量级且有针对性的测试验证 Spring MVC 应用程序的大部分功能。您可以单独使用它来执行请求并使用 Hamcrest 验证响应,或者通过`MockMvcTester`提供使用 AssertJ 的流畅 API。最后,您还可以通过WebTestClientAPI(其中 MockMvc 已插入为服务器以处理请求)使用它。

MockMvc is a server side test framework that lets you verify most of the functionality of a Spring MVC application using lightweight and targeted tests. You can use it on its own to perform requests and to verify responses using Hamcrest, or through MockMvcTester that provides a fluent API using AssertJ. Finally, you can also use it through the WebTestClient API with MockMvc plugged in as the server to handle requests with.