@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。