設定 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 回應 body 或 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
。