@ContextConfiguration
@ContextConfiguration
是一個註解,可以應用於測試類別,以組態中繼資料,該中繼資料用於判斷如何為整合測試載入和組態 ApplicationContext
。具體來說,@ContextConfiguration
宣告應用程式 Context 資源 locations
或用於載入 Context 的元件 classes
。
資源位置通常是位於類路徑中的 XML 組態檔或 Groovy Script,而元件類別通常是 @Configuration
類別。但是,資源位置也可以參考檔案系統中的檔案和 Script,而元件類別可以是 @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 提供了繼承資源位置或組態類別以及由父類別或封閉類別宣告的 Context 初始化器的支援。 |
請參閱 Context 管理、@Nested
測試類別組態,以及 @ContextConfiguration
javadoc 以了解更多詳細資訊。