使用元件類進行上下文配置
要透過使用元件類(參見基於Java的容器配置)為測試載入ApplicationContext,你可以使用@ContextConfiguration註解你的測試類,並使用包含元件類引用的陣列配置classes屬性。以下示例展示瞭如何實現:
-
Java
-
Kotlin
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) (1)
class MyTest {
// class body...
}
| 1 | 指定元件類。 |
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from AppConfig and TestConfig
@ContextConfiguration(classes = [AppConfig::class, TestConfig::class]) (1)
class MyTest {
// class body...
}
| 1 | 指定元件類。 |
|
元件類
“元件類”一詞可以指以下任何一種:
有關元件類的配置和語義的更多資訊,請參閱 |
如果你省略@ContextConfiguration註解中的classes屬性,TestContext框架會嘗試檢測預設配置類的存在。具體來說,AnnotationConfigContextLoader和AnnotationConfigWebContextLoader會檢測測試類的所有static巢狀類,這些類滿足@Configuration javadoc中指定的配置類實現要求。請注意,配置類的名稱是任意的。此外,如果需要,一個測試類可以包含多個static巢狀配置類。在下面的示例中,OrderServiceTest類聲明瞭一個名為Config的static巢狀配置類,該類會自動用於為測試類載入ApplicationContext。
-
Java
-
Kotlin
@SpringJUnitConfig (1)
// ApplicationContext will be loaded from the static nested Config class
class OrderServiceTest {
@Configuration
static class Config {
// this bean will be injected into the OrderServiceTest class
@Bean
OrderService orderService() {
OrderService orderService = new OrderServiceImpl();
// set properties, etc.
return orderService;
}
}
@Autowired
OrderService orderService;
@Test
void testOrderService() {
// test the orderService
}
}
| 1 | 從巢狀的Config類載入配置資訊。 |
@SpringJUnitConfig (1)
// ApplicationContext will be loaded from the nested Config class
class OrderServiceTest {
@Autowired
lateinit var orderService: OrderService
@Configuration
class Config {
// this bean will be injected into the OrderServiceTest class
@Bean
fun orderService(): OrderService {
// set properties, etc.
return OrderServiceImpl()
}
}
@Test
fun testOrderService() {
// test the orderService
}
}
| 1 | 從巢狀的Config類載入配置資訊。 |