定义预期

可以通过在执行请求后附加一个或多个 andExpect(..) 调用来定义预期,如下例所示。一旦一个预期失败,将不会断言其他预期。

  • Java

  • Kotlin

// 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(..) 保证所有提供的预期都将被断言,并且所有失败都会被跟踪和报告。

  • Java

  • Kotlin

// 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 MVC 特定的方面,例如哪个控制器方法处理了请求,是否抛出并处理了异常,Model 的内容是什么,选择了哪个视图,添加了哪些 flash 属性等等。它们还允许你检查 Servlet 特定的方面,例如请求和会话属性。

以下测试断言绑定或验证失败

  • Java

  • Kotlin

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 静态导入的:

  • Java

  • Kotlin

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() 方法以及 print() 方法的另外两个变体,一个接受 OutputStream,另一个接受 Writer。例如,调用 print(System.err) 将结果数据打印到 System.err,而调用 print(myWriter) 将结果数据打印到自定义 writer。如果你希望将结果数据记录下来而不是打印,可以调用 log() 方法,它将在 org.springframework.test.web.servlet.result 日志类别下将结果数据记录为一条 DEBUG 消息。

在某些情况下,你可能希望直接访问结果并验证一些无法通过其他方式验证的内容。这可以通过在所有其他预期后附加 .andReturn() 来实现,如下例所示:

  • Java

  • Kotlin

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

如果所有测试都重复相同的预期,你可以在构建 MockMvc 实例时设置一次公共预期,如下例所示:

  • Java

  • Kotlin

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 实例,否则无法覆盖它们。

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

  • Java

  • Kotlin

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 表达式验证生成的链接。

  • Java

  • Kotlin

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")
	}
}