配置 MockMvcTester

MockMvcTester 可以通过两种方式进行设置。一种是直接指向你想测试的控制器并以编程方式配置 Spring MVC 基础设施。第二种是指向包含 Spring MVC 和控制器基础设施的 Spring 配置。

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

要设置 MockMvcTester 来测试特定控制器,请使用以下方法:

  • Java

  • Kotlin

public class AccountControllerStandaloneTests {

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

	// ...

}
class AccountControllerStandaloneTests {

	val mockMvc = MockMvcTester.of(AccountController())

	// ...

}

要通过 Spring 配置设置 MockMvcTester,请使用以下方法:

  • Java

  • Kotlin

@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)

	// ...

}

只要注册了相关的 HttpMessageConverterMockMvcTester 就可以将 JSON 响应体或 JSONPath 表达式的结果转换为你的一个领域对象。

如果你使用 Jackson 将内容序列化为 JSON,以下示例注册了转换器:

  • Java

  • Kotlin

@SpringJUnitWebConfig(ApplicationWebConfiguration.class)
class AccountControllerIntegrationTests {

	private final MockMvcTester mockMvc;

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

	// ...

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

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

	// ...

}
上述假设转换器已注册为 Bean。

最后,如果你手边有一个 MockMvc 实例,可以通过将该 MockMvc 实例提供给 create 工厂方法来创建 MockMvcTester