|
此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
@ContextConfiguration
@ContextConfiguration是一个注解,可以应用于测试类进行配置
元数据,用于确定如何加载和配置ApplicationContext为
集成测试。具体说来@ContextConfiguration声明应用程序上下文
资源locations或组件classes用于加载上下文。
资源位置通常是 XML 配置文件或 Groovy 脚本,位于
classpath,而组件类通常是@Configuration类。然而
资源位置还可以引用文件系统和组件中的文件和脚本
类可以是@Component类@Service类,依此类推。有关更多详细信息,请参阅组件类。
以下示例显示了@ContextConfiguration引用 XML 的注释
文件:
-
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测试类配置,
和@ContextConfigurationjavadocs 了解更多详情。