使用XML资源进行上下文配置
要使用XML配置文件为测试加载ApplicationContext,请在测试类上添加@ContextConfiguration注解,并使用一个包含XML配置元数据资源位置的数组来配置locations属性。普通的或相对的路径(例如context.xml)被视为相对于测试类所在包的类路径资源。以斜杠开头的路径被视为绝对类路径位置(例如/org/example/config.xml)。表示资源URL的路径(即以classpath:、file:、http:等为前缀的路径)将按原样使用。
- Java
- Kotlin
@ExtendWith(SpringExtension.class)
// ApplicationContext将从类路径根目录下的"/app-config.xml"和"/test-config.xml"加载
@ContextConfiguration(locations = {"/app-config.xml", "/test-config.xml"}) 1
class MyTest {
// 类体...
}
将locations属性设置为XML文件列表。
@ExtendWith(SpringExtension::class)
// ApplicationContext将从类路径根目录下的"/app-config.xml"和"/test-config.xml"加载
@ContextConfiguration(locations = ["/app-config.xml", "/test-config.xml"]) 1
class MyTest {
// 类体...
}
将locations属性设置为XML文件列表。
@ContextConfiguration 通过标准的 Java value 属性支持为 locations 属性设置别名。因此,如果你不需要在 @ContextConfiguration 中声明额外的属性,就可以省略 locations 属性名的声明,而是使用以下示例中展示的简写格式来指定资源位置:
- Java
- Kotlin
@ExtendWith(SpringExtension.class)
@ContextConfiguration({"/app-config.xml", "/test-config.xml"}) 1
class MyTest {
// class body...
}
不使用
locations属性来指定 XML 文件。
@ExtendWith(SpringExtension::class)
@ContextConfiguration("/app-config.xml", "/test-config.xml") 1
class MyTest {
// class body...
}
不使用
locations属性来指定 XML 文件。
如果你在@ContextConfiguration注解中省略了locations和value属性,TestContext框架会尝试检测默认的XML资源位置。具体来说,GenericXmlContextLoader和GenericXmlWebContextLoader会根据测试类的名称来检测默认位置。如果你的类名为com.example.MyTest,GenericXmlContextLoader会从"classpath:com/example/MyTest-context.xml"加载你的应用上下文。以下示例展示了如何实现这一点:
- Java
- Kotlin
@ExtendWith(SpringExtension.class)
// ApplicationContext将从以下路径加载:
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration 1
class MyTest {
// 类体...
}
从默认位置加载配置。
@ExtendWith(SpringExtension::class)
// ApplicationContext将从以下路径加载:
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration 1
class MyTest {
// 类体...
}
从默认位置加载配置。