使用 XML 资源配置上下文
要通过使用 XML 配置文件为你的测试加载 ApplicationContext
,可以使用 @ContextConfiguration
注解你的测试类,并通过 locations
属性配置一个包含 XML 配置元数据资源位置的数组。普通的或相对路径(例如 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 {
// class body...
}
将 locations 属性设置为 XML 文件列表。
@ExtendWith(SpringExtension::class)
// ApplicationContext 将从类路径根目录下的 "/app-config.xml" 和
// "/test-config.xml" 加载
@ContextConfiguration(locations = ["/app-config.xml", "/test-config.xml"]) 1
class MyTest {
// class body...
}
将 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 {
// class body...
}
从默认位置加载配置。
@ExtendWith(SpringExtension::class)
// ApplicationContext 将从
// "classpath:com/example/MyTest-context.xml" 加载
@ContextConfiguration 1
class MyTest {
// class body...
}
从默认位置加载配置。