@ContextConfiguration
@ContextConfiguration
@ContextConfiguration是一个注解,可以应用于测试类,用于配置元数据,这些元数据用于确定如何加载和配置集成测试所需的ApplicationContext。具体来说,@ContextConfiguration声明了用于加载应用程序上下文的资源“locations”或组件“classes”。
资源位置通常是位于类路径(classpath)中的XML配置文件或Groovy脚本,而组件类通常是指标有@Configuration注解的类。不过,资源位置也可以指文件系统中的文件和脚本;同样,组件类也可以是标有@Component、@Service等注解的类。有关更多详细信息,请参阅组件类。
以下示例展示了一个@ContextConfiguration注释,该注释引用了一个XML文件:
- Java
- Kotlin
@ContextConfiguration("/test-config.xml") 1
class XmlApplicationContextTests {
// class body...
}
指的是一个XML文件。
@ContextConfiguration("/test-config.xml") 1
class XmlApplicationContextTests {
// class body...
}
指的是一个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中的任意一种。
以下示例同时使用了位置(location)和加载器(loader):
- Java
- Kotlin
@ContextConfiguration(locations = "/test-context.xml", loader = CustomContextLoader.class) 1
class CustomLoaderXmlApplicationContextTests {
// class body...
}
同时配置位置(location)和自定义加载器(custom loader)。
@ContextConfiguration("/test-context.xml", loader = CustomContextLoader::class) 1
class CustomLoaderXmlApplicationContextTests {
// class body...
}
同时配置位置(location)和自定义加载器(custom loader)。
@ContextConfiguration 支持继承由超类或包含类声明的资源位置、配置类以及上下文初始化器。
有关更多详细信息,请参阅上下文管理、@嵌套测试类配置,以及@ContextConfiguration的Java文档。