@ContextConfiguration
@ContextConfiguration 是一個註解,可應用於測試類,用於配置元資料,以確定如何為整合測試載入和配置 ApplicationContext。具體來說,@ContextConfiguration 聲明瞭用於載入上下文的應用程式上下文資源 locations 或元件 classes。
資源位置通常是位於類路徑中的 XML 配置檔案或 Groovy 指令碼,而元件類通常是 @Configuration 類。然而,資源位置也可以指檔案系統中的檔案和指令碼,元件類可以是 @Component 類、@Service 類等。有關詳細資訊,請參閱元件類。
以下示例顯示了一個引用 XML 檔案的 @ContextConfiguration 註解
-
Java
-
Kotlin
@ContextConfiguration("/test-config.xml") (1)
class XmlApplicationContextTests {
// class body...
}
| 1 | 引用 XML 檔案。 |
@ContextConfiguration("/test-config.xml") (1)
class XmlApplicationContextTests {
// class body...
}
| 1 | 引用 XML 檔案。 |
以下示例顯示了一個引用類的 @ContextConfiguration 註解
-
Java
-
Kotlin
@ContextConfiguration(classes = TestConfig.class) (1)
class ConfigClassApplicationContextTests {
// class body...
}
| 1 | 引用類。 |
@ContextConfiguration(classes = [TestConfig::class]) (1)
class ConfigClassApplicationContextTests {
// class body...
}
| 1 | 引用類。 |
作為宣告資源位置或元件類的替代或補充,您可以使用 @ContextConfiguration 宣告 ApplicationContextInitializer 類。以下示例顯示了這種情況
-
Java
-
Kotlin
@ContextConfiguration(initializers = CustomContextInitializer.class) (1)
class ContextInitializerTests {
// class body...
}
| 1 | 宣告初始化器類。 |
@ContextConfiguration(initializers = [CustomContextInitializer::class]) (1)
class ContextInitializerTests {
// class body...
}
| 1 | 宣告初始化器類。 |
您還可以選擇使用 @ContextConfiguration 宣告 ContextLoader 策略。但是請注意,您通常不需要顯式配置載入器,因為預設載入器支援 initializers 以及資源 locations 或元件 classes。
以下示例同時使用了位置和載入器
-
Java
-
Kotlin
@ContextConfiguration(locations = "/test-context.xml", loader = CustomContextLoader.class) (1)
class CustomLoaderXmlApplicationContextTests {
// class body...
}
| 1 | 配置位置和自定義載入器。 |
@ContextConfiguration("/test-context.xml", loader = CustomContextLoader::class) (1)
class CustomLoaderXmlApplicationContextTests {
// class body...
}
| 1 | 配置位置和自定義載入器。 |
@ContextConfiguration 支援繼承父類或外部類宣告的資源位置或配置類以及上下文初始化器。 |
有關更多詳細資訊,請參閱上下文管理、@Nested 測試類配置以及 @ContextConfiguration 的 Javadoc。