配置 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)
// ...
}
只要註冊了相關的 HttpMessageConverter,MockMvcTester 就可以將 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 例項,您可以透過使用 create 工廠方法提供要使用的 MockMvc 例項來建立 MockMvcTester。