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