使用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 {
	// 类主体...
}
1 将locations属性设置为XML文件列表。
@ExtendWith(SpringExtension::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

  • Kotlin

@ExtendWith(SpringExtension.class)
@ContextConfiguration({"/app-config.xml", "/test-config.xml"}) (1)
class MyTest {
	// 类主体...
}
1 不使用locations属性指定XML文件。
@ExtendWith(SpringExtension::class)
@ContextConfiguration("/app-config.xml", "/test-config.xml") (1)
class MyTest {
	// 类主体...
}
1 不使用locations属性指定XML文件。

如果从@ContextConfiguration注解中同时省略locationsvalue属性,则TestContext框架会尝试检测默认的XML资源位置。具体来说,GenericXmlContextLoaderGenericXmlWebContextLoader会基于测试类的名称检测默认位置。如果您的类名为com.example.MyTestGenericXmlContextLoader将从"classpath:com/example/MyTest-context.xml"加载您的应用上下文。以下示例展示了如何实现:

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext将从"classpath:com/example/MyTest-context.xml"加载
@ContextConfiguration (1)
class MyTest {
	// 类主体...
}
1 从默认位置加载配置。
@ExtendWith(SpringExtension::class)
// ApplicationContext将从"classpath:com/example/MyTest-context.xml"加载
@ContextConfiguration (1)
class MyTest {
	// 类主体...
}
1 从默认位置加载配置。