@ContextConfiguration
@ContextConfiguration
@ContextConfiguration
是一个可以应用于测试类的注解,用于配置元数据,以确定如何加载和配置 ApplicationContext
以进行集成测试。具体而言,@ContextConfiguration
声明了用于加载上下文的应用程序上下文资源 locations
或组件 classes
。
资源位置通常是位于类路径中的 XML 配置文件或 Groovy 脚本,而组件类通常是 @Configuration
类。然而,资源位置也可以指文件系统中的文件和脚本,组件类可以是 @Component
类、@Service
类等。有关更多详细信息,请参见 Component Classes。
以下示例显示了一个 @ContextConfiguration
注解,它引用了一个 XML 文件:
- Java
- Kotlin
@ContextConfiguration("/test-config.xml") 1
class XmlApplicationContextTests {
// 类体...
}
引用一个 XML 文件。
@ContextConfiguration("/test-config.xml") 1
class XmlApplicationContextTests {
// 类体...
}
引用一个 XML 文件。
以下示例展示了一个 @ContextConfiguration
注解,它引用了一个类:
- Java
- Kotlin
@ContextConfiguration(classes = TestConfig.class) 1
class ConfigClassApplicationContextTests {
// class body...
}
引用一个类。
@ContextConfiguration(classes = [TestConfig::class]) 1
class ConfigClassApplicationContextTests {
// class body...
}
引用一个类。
作为声明资源位置或组件类的替代方法或补充,您可以使用 @ContextConfiguration
来声明 ApplicationContextInitializer
类。以下示例展示了这种情况:
- Java
- Kotlin
@ContextConfiguration(initializers = CustomContextInitializer.class) 1
class ContextInitializerTests {
// class body...
}
声明一个初始化器类。
@ContextConfiguration(initializers = [CustomContextInitializer::class]) 1
class ContextInitializerTests {
// class body...
}
声明一个初始化器类。
您可以选择使用 @ContextConfiguration
来声明 ContextLoader
策略。不过,请注意,您通常不需要显式配置加载器,因为默认加载器支持 initializers
和资源 locations
或组件 classes
。
以下示例同时使用了位置和加载器:
- Java
- Kotlin
@ContextConfiguration(locations = "/test-context.xml", loader = CustomContextLoader.class) 1
class CustomLoaderXmlApplicationContextTests {
// class body...
}
配置位置和自定义加载器。
@ContextConfiguration("/test-context.xml", loader = CustomContextLoader::class) 1
class CustomLoaderXmlApplicationContextTests {
// class body...
}
配置位置和自定义加载器。
@ContextConfiguration
提供了对继承资源位置或配置类的支持,以及由超类或封闭类声明的上下文初始化器。
请参阅 Context Management、@Nested test class configuration 和 @ContextConfiguration
的 javadocs 以获取更多详细信息。