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

配置 MockMvcTester

MockMvcTester 可以通过两种方式之一进行设置。一种是直接指向您要测试的控制器,并以编程方式配置 Spring MVC 基础设施。另一种是指向包含 Spring MVC 和控制器基础设施的 Spring 配置。spring-doc.cadn.net.cn

有关这两种模式的比较,请参阅设置选项

要为测试特定控制器而设置 MockMvcTester,请使用以下方式:spring-doc.cadn.net.cn

public class AccountControllerStandaloneTests {

	private final MockMvcTester mockMvc = MockMvcTester.of(new AccountController());

	// ...

}
class AccountControllerStandaloneTests {

	val mockMvc = MockMvcTester.of(AccountController())

	// ...

}

要通过 Spring 配置设置 MockMvcTester,请使用以下方式:spring-doc.cadn.net.cn

@SpringJUnitWebConfig(ApplicationWebConfiguration.class)
class AccountControllerIntegrationTests {

	private final MockMvcTester mockMvc;

	AccountControllerIntegrationTests(@Autowired WebApplicationContext wac) {
		this.mockMvc = MockMvcTester.from(wac);
	}

	// ...

}
@SpringJUnitWebConfig(ApplicationWebConfiguration::class)
class AccountControllerIntegrationTests(@Autowired wac: WebApplicationContext) {

	private val mockMvc = MockMvcTester.from(wac)

	// ...

}

MockMvcTester 可以将 JSON 响应体或 JSONPath 表达式的结果转换为您自己的领域对象,前提是已注册了相应的 HttpMessageConverterspring-doc.cadn.net.cn

如果你使用 Jackson 将内容序列化为 JSON,以下示例会注册该转换器:spring-doc.cadn.net.cn

@SpringJUnitWebConfig(ApplicationWebConfiguration.class)
class AccountControllerIntegrationTests {

	private final MockMvcTester mockMvc;

	AccountControllerIntegrationTests(@Autowired WebApplicationContext wac) {
		this.mockMvc = MockMvcTester.from(wac).withHttpMessageConverters(
				List.of(wac.getBean(AbstractJacksonHttpMessageConverter.class)));
	}

	// ...

}
@SpringJUnitWebConfig(ApplicationWebConfiguration::class)
class AccountControllerIntegrationTests(@Autowired wac: WebApplicationContext) {

	private val mockMvc = MockMvcTester.from(wac).withHttpMessageConverters(
		listOf(wac.getBean(AbstractJacksonHttpMessageConverter::class.java)))

	// ...

}
以上假设该转换器已注册为一个 Bean。

最后,如果你手头有一个 MockMvc 实例,可以通过将该 MockMvcTester 实例传递给 MockMvc 工厂方法来创建一个 createspring-doc.cadn.net.cn