此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

执行请求

本节介绍如何单独使用 MockMvc 来执行请求和验证响应。如果通过WebTestClient请参阅有关编写测试的相应部分。spring-doc.cadn.net.cn

要执行使用任何 HTTP 方法的请求,如以下示例所示:spring-doc.cadn.net.cn

// 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这样就不会对多部分进行实际解析 请求。相反,您必须将其设置为类似于以下示例:spring-doc.cadn.net.cn

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 模板样式中指定查询参数,如以下示例所示:spring-doc.cadn.net.cn

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

您还可以添加表示查询或表单的 Servlet 请求参数 参数,如以下示例所示:spring-doc.cadn.net.cn

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

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

如果应用程序代码依赖于 Servlet 请求参数并且不检查查询 字符串显式(最常见的情况),使用哪个选项并不重要。 但是请记住,URI 模板提供的查询参数是解码的 而请求参数通过param(…​)方法预计已经 被解码。spring-doc.cadn.net.cn

在大多数情况下,最好将上下文路径和 Servlet 路径留在 请求 URI。如果必须使用完整的请求 URI 进行测试,请务必将contextPathservletPath相应地,以便请求映射正常工作,如以下示例所示 显示:spring-doc.cadn.net.cn

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每个执行的请求。相反,您可以设置默认请求 属性,如以下示例所示:spring-doc.cadn.net.cn

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 无关紧要,因为 必须在每个请求中指定它们。spring-doc.cadn.net.cn