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

定义期望

您可以通过附加一个或多个andExpect(..)之后的调用 执行请求,如下例所示。一旦一个期望落空, 不会断言其他期望。spring-doc.cadn.net.cn

// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.*

mockMvc.perform(get("/accounts/1")).andExpect(status().isOk());
import org.springframework.test.web.servlet.get

mockMvc.get("/accounts/1").andExpect {
	status { isOk() }
}

您可以通过附加andExpectAll(..)执行 请求,如下例所示。与andExpect(..),andExpectAll(..)保证所有提供的期望都将被断言,并且 将跟踪和报告所有失败。spring-doc.cadn.net.cn

// static import of MockMvcRequestBuilders.* and MockMvcResultMatchers.*

mockMvc.perform(get("/accounts/1")).andExpectAll(
	status().isOk(),
	content().contentType("application/json;charset=UTF-8"));
import org.springframework.test.web.servlet.get

mockMvc.get("/accounts/1").andExpectAll {
	status { isOk() }
	content { contentType(APPLICATION_JSON) }
}

MockMvcResultMatchers.*提供了许多期望,其中一些是更进一步的 嵌套了更详细的期望。spring-doc.cadn.net.cn

期望分为两大类。第一类断言验证 响应的属性(例如,响应状态、标头和内容)。 这些是要断言的最重要的结果。spring-doc.cadn.net.cn

第二类断言超出了响应的范围。这些断言允许您 检查 Spring MVC 特定的方面,例如哪个控制器方法处理了 请求,是否引发并处理了异常,模型的内容是什么, 选择了什么视图,添加了哪些 Flash 属性,等等。他们还让您 检查 Servlet 特定的方面,比如 request 和 session 属性。spring-doc.cadn.net.cn

以下测试断言绑定或验证失败:spring-doc.cadn.net.cn

mockMvc.perform(post("/persons"))
	.andExpect(status().isOk())
	.andExpect(model().attributeHasErrors("person"));
import org.springframework.test.web.servlet.post

mockMvc.post("/persons").andExpect {
	status { isOk() }
	model {
		attributeHasErrors("person")
	}
}

很多时候,在编写测试时,转储执行的 请求。您可以按如下方式执行此作,其中print()是从MockMvcResultHandlers:spring-doc.cadn.net.cn

mockMvc.perform(post("/persons"))
	.andDo(print())
	.andExpect(status().isOk())
	.andExpect(model().attributeHasErrors("person"));
import org.springframework.test.web.servlet.post

mockMvc.post("/persons").andDo {
		print()
	}.andExpect {
		status { isOk() }
		model {
			attributeHasErrors("person")
		}
	}

只要请求处理不会导致未经处理的异常,print()方法 将所有可用的结果数据打印到System.out.还有一个log()method 和 的print()方法,该方法接受OutputStream和 一个接受Writer.例如,调用print(System.err)打印结果 data 到System.err,在调用print(myWriter)将结果数据打印到自定义 作家。如果要记录结果数据而不是打印结果数据,可以调用log()方法,该方法将结果数据记录为单个DEBUGmessageorg.springframework.test.web.servlet.resultlogging 类别。spring-doc.cadn.net.cn

在某些情况下,您可能希望直接访问结果并验证 否则无法验证。这可以通过附加.andReturn()毕竟 其他期望,如下例所示:spring-doc.cadn.net.cn

MvcResult mvcResult = mockMvc.perform(post("/persons")).andExpect(status().isOk()).andReturn();
// ...
var mvcResult = mockMvc.post("/persons").andExpect { status { isOk() } }.andReturn()
// ...

如果所有测试都重复相同的期望值,则可以在以下情况下设置一次通用期望值 构建MockMvcinstance,如下例所示:spring-doc.cadn.net.cn

standaloneSetup(new SimpleController())
	.alwaysExpect(status().isOk())
	.alwaysExpect(content().contentType("application/json;charset=UTF-8"))
	.build()
// Not possible in Kotlin until {kotlin-issues}/KT-22208 is fixed

请注意,通用期望始终适用,如果没有 创建单独的MockMvc实例。spring-doc.cadn.net.cn

当 JSON 响应内容包含使用 Spring HATEOAS 创建的超媒体链接时,您可以验证 使用 JsonPath 表达式生成的链接,如下例所示:spring-doc.cadn.net.cn

mockMvc.perform(get("/people").accept(MediaType.APPLICATION_JSON))
	.andExpect(jsonPath("$.links[?(@.rel == 'self')].href").value("http://localhost:8080/people"));
mockMvc.get("/people") {
	accept(MediaType.APPLICATION_JSON)
}.andExpect {
	jsonPath("$.links[?(@.rel == 'self')].href") {
		value("http://localhost:8080/people")
	}
}

当 XML 响应内容包含使用 Spring HATEOAS 创建的超媒体链接时,您可以验证 使用 XPath 表达式生成的链接:spring-doc.cadn.net.cn

Map<String, String> ns = Collections.singletonMap("ns", "http://www.w3.org/2005/Atom");
mockMvc.perform(get("/handle").accept(MediaType.APPLICATION_XML))
	.andExpect(xpath("/person/ns:link[@rel='self']/@href", ns).string("http://localhost:8080/people"));
val ns = mapOf("ns" to "http://www.w3.org/2005/Atom")
mockMvc.get("/handle") {
	accept(MediaType.APPLICATION_XML)
}.andExpect {
	xpath("/person/ns:link[@rel='self']/@href", ns) {
		string("http://localhost:8080/people")
	}
}