使用元件類別進行情境組態
若要使用元件類別 (請參閱基於 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
會偵測測試類別的所有靜態巢狀類別,這些類別符合 @Configuration
javadoc 中指定的組態類別實作要求。請注意,組態類別的名稱是任意的。此外,如果需要,一個測試類別可以包含多個靜態巢狀組態類別。在以下範例中,OrderServiceTest
類別宣告了一個名為 Config
的靜態巢狀組態類別,該類別會自動用於為測試類別載入 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 類別載入組態資訊。 |