Performing Requests

此部分展示了如何单独使用 MockMvc 来执行请求和验证响应。如果您通过 WebTestClient 使用 MockMvc,请改参见 Writing Tests 中的相应部分。

This section shows how to use MockMvc on its own to perform requests and verify responses. If using MockMvc through the WebTestClient please see the corresponding section on Writing Tests instead.

要执行使用任何 HTTP 方法的请求,如以下示例所示:

To perform requests that use any HTTP method, as the following example shows:

  • Java

  • Kotlin

// static import of MockMvcRequestBuilders.*

mockMvc.perform(post("/hotels/{id}", 42).accept(MediaType.APPLICATION_JSON));
import org.springframework.test.web.servlet.post

mockMvc.post("/hotels/{id}", 42) {
	accept = MediaType.APPLICATION_JSON
}

你还可以执行文件上传请求,在内部使用 MockMultipartHttpServletRequest,这样就没有对 multipart 请求的实际解析。相反,你必须将其设置为与以下示例类似:

You can also perform file upload requests that internally use MockMultipartHttpServletRequest so that there is no actual parsing of a multipart request. Rather, you have to set it up to be similar to the following example:

  • Java

  • Kotlin

mockMvc.perform(multipart("/doc").file("a1", "ABC".getBytes("UTF-8")));
import org.springframework.test.web.servlet.multipart

mockMvc.multipart("/doc") {
	file("a1", "ABC".toByteArray(charset("UTF8")))
}

您可以使用 URI 模板样式指定查询参数,如下例所示:

You can specify query parameters in URI template style, as the following example shows:

  • Java

  • Kotlin

mockMvc.perform(get("/hotels?thing={thing}", "somewhere"));
mockMvc.get("/hotels?thing={thing}", "somewhere")

您还可以添加 Servlet 请求参数,表示 query 或 formparameters,如下例所示:

You can also add Servlet request parameters that represent either query or form parameters, as the following example shows:

  • Java

  • Kotlin

mockMvc.perform(get("/hotels").param("thing", "somewhere"));
import org.springframework.test.web.servlet.get

mockMvc.get("/hotels") {
	param("thing", "somewhere")
}

如果应用程序代码依赖于 Servlet 请求参数,并且没有明确检查 querystring(这种情况最常见),您使用哪种选项无关紧要。但请记住,使用 URI 模板提供的查询参数已解码,而通过 param(…​) 方法提供的请求参数应已解码。

If application code relies on Servlet request parameters and does not check the query string explicitly (as is most often the case), it does not matter which option you use. Keep in mind, however, that query parameters provided with the URI template are decoded while request parameters provided through the param(…​) method are expected to already be decoded.

在大多数情况下,最好将上下文路径和 Servlet 路径从请求 URI 中排除出去。如果您必须使用完整的请求 URI 进行测试,请务必相应地设置 contextPathservletPath,以便请求映射正常工作,如下例所示:

In most cases, it is preferable to leave the context path and the Servlet path out of the request URI. If you must test with the full request URI, be sure to set the contextPath and servletPath accordingly so that request mappings work, as the following example shows:

  • Java

  • Kotlin

mockMvc.perform(get("/app/main/hotels/{id}").contextPath("/app").servletPath("/main"))
import org.springframework.test.web.servlet.get

mockMvc.get("/app/main/hotels/{id}") {
	contextPath = "/app"
	servletPath = "/main"
}

在前面的示例中,在每个执行的请求中设置 contextPathservletPath 会很麻烦。相反,您可以设置默认请求属性,如下例所示:

In the preceding example, it would be cumbersome to set the contextPath and servletPath with every performed request. Instead, you can set up default request properties, as the following example shows:

  • Java

  • Kotlin

class MyWebTests {

	MockMvc mockMvc;

	@BeforeEach
	void setup() {
		mockMvc = standaloneSetup(new AccountController())
			.defaultRequest(get("/")
			.contextPath("/app").servletPath("/main")
			.accept(MediaType.APPLICATION_JSON)).build();
	}
}
// Not possible in Kotlin until {kotlin-issues}/KT-22208 is fixed

前面的属性影响通过 MockMvc 实例执行的每个请求。如果在给定请求上也指定了相同的属性,则它将覆盖默认值。这就是为什么默认请求中的 HTTP 方法和 URI 无关紧要的原因,因为它们必须在每个请求中指定。

The preceding properties affect every request performed through the MockMvc instance. If the same property is also specified on a given request, it overrides the default value. That is why the HTTP method and URI in the default request do not matter, since they must be specified on every request.