使用 XML 资源进行上下文配置
要通过使用 XML 配置文件为测试加载 ApplicationContext
,请使用 @ContextConfiguration
注释您的测试类,并使用包含 XML 配置元数据资源位置的数组配置 locations
属性。
普通或相对路径(例如 context.xml
)被视为相对于定义测试类的包的类路径资源。
以斜杠开头的路径被视为绝对类路径位置(例如 /org/example/config.xml
)。
表示资源 URL 的路径(即以 classpath:
、file:
、http:
等为前缀的路径)将 按原样 使用。
- Java
-
@ExtendWith(SpringExtension.class) // ApplicationContext will be loaded from "/app-config.xml" and // "/test-config.xml" in the root of the classpath @ContextConfiguration(locations = {"/app-config.xml", "/test-config.xml"}) [id="CO1-1"][id="CO1-1"][id="CO1-1"](1) class MyTest { // class body... }
<1> 将 locations 属性设置为 XML 文件列表。
- Kotlin
-
@ExtendWith(SpringExtension::class) // ApplicationContext will be loaded from "/app-config.xml" and // "/test-config.xml" in the root of the classpath @ContextConfiguration(locations = ["/app-config.xml", "/test-config.xml"]) [id="CO2-1"][id="CO1-2"][id="CO2-1"](1) class MyTest { // class body... }
<1> 将 locations 属性设置为 XML 文件列表。
@ContextConfiguration
通过标准 Java value
属性支持 locations
属性的别名。
因此,如果您不需要在 @ContextConfiguration
中声明其他属性,则可以省略 locations
属性名称的声明,并使用以下示例中所示的简写格式声明资源位置:
- Java
-
@ExtendWith(SpringExtension.class) @ContextConfiguration({"/app-config.xml", "/test-config.xml"}) [id="CO3-1"]1 class MyTest { // class body... }
<1> 不使用 `locations` 属性指定 XML 文件。
- Kotlin
-
@ExtendWith(SpringExtension::class) @ContextConfiguration("/app-config.xml", "/test-config.xml") [id="CO4-1"][id="CO1-3"][id="CO4-1"](1) class MyTest { // class body... }
<1> 不使用 `locations` 属性指定 XML 文件。
如果您从 @ContextConfiguration
注解中省略 locations
和 value
属性,
TestContext 框架会尝试检测默认的 XML 资源位置。具体来说,GenericXmlContextLoader
和 GenericXmlWebContextLoader
会根据测试类的名称检测默认位置。
如果您的类名为 com.example.MyTest
,GenericXmlContextLoader
会从
"classpath:com/example/MyTest-context.xml"
加载您的应用程序上下文。
以下示例演示了如何实现:
- Java
-
@ExtendWith(SpringExtension.class) // ApplicationContext will be loaded from // "classpath:com/example/MyTest-context.xml" @ContextConfiguration [id="CO5-1"][id="CO1-4"][id="CO5-1"](1) class MyTest { // class body... }
<1> 从默认位置加载配置。
- Kotlin
-
@ExtendWith(SpringExtension::class) // ApplicationContext will be loaded from // "classpath:com/example/MyTest-context.xml" @ContextConfiguration [id="CO6-1"][id="CO1-5"][id="CO6-1"](1) class MyTest { // class body... }
<1> 从默认位置加载配置。