使用 XML 资源进行上下文配置

要通过 XML 配置文件为您的测试加载 ApplicationContext,请使用 @ContextConfiguration 注解您的测试类,并使用包含 XML 配置元数据资源位置的数组配置 locations 属性。一个简单或相对路径(例如,context.xml)被视为相对于定义测试类的包的类路径资源。以斜杠开头的路径被视为绝对类路径位置(例如,/org/example/config.xml)。表示资源 URL 的路径(即,以 classpath:file:http: 等前缀开头的路径)将按原样使用。

  • Java

  • 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"}) (1)
class MyTest {
	// class body...
}
1 将 locations 属性设置为 XML 文件列表。
@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"]) (1)
class MyTest {
	// class body...
}
1 将 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...
}
1 不使用 locations 属性指定 XML 文件。
@ExtendWith(SpringExtension::class)
@ContextConfiguration("/app-config.xml", "/test-config.xml") (1)
class MyTest {
	// class body...
}
1 不使用 locations 属性指定 XML 文件。

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

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 从默认位置加载配置。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 从默认位置加载配置。
© . This site is unofficial and not affiliated with VMware.