加载 WebApplicationContext
要让 TestContext 框架加载 WebApplicationContext 而不是标准的 ApplicationContext,
可以在相应测试类上标注 @WebAppConfiguration。
在测试类上使用 @WebAppConfiguration 会指示 TestContext 框架(TCF)为你的集成测试加载
WebApplicationContext(WAC)。在幕后,TCF 会确保创建 MockContextImpl 并将其提供给
测试的 WAC。默认情况下,MockContextImpl 的基础资源路径为 src/main/webapp。
这会被解释为相对于 JVM 根目录的路径(通常为项目路径)。如果你熟悉 Maven 项目的
Web 应用目录结构,就会知道 src/main/webapp 是 WAR 根目录的默认位置。
如需覆盖该默认值,可以为 @WebAppConfiguration 提供另一个路径
(例如 @WebAppConfiguration("src/test/webapp"))。如果希望从 classpath 而不是
文件系统引用基础资源路径,可以使用 Infra 的 classpath: 前缀。
请注意,Infra 对 WebApplicationContext 实现的测试支持与对标准 ApplicationContext
实现的支持一致。使用 WebApplicationContext 测试时,你可以通过
@ContextConfiguration 声明 XML 配置文件、Groovy 脚本或 @Configuration 类。
也可以使用其他测试注解,例如 @ActiveProfiles、@TestExecutionListeners、@Sql、
@Rollback 等。
本节剩余示例展示了加载 WebApplicationContext 的多种配置选项。
下面示例展示了 TestContext 框架对“约定优于配置”的支持:
-
Conventions
@ExtendWith(InfraExtension.class)
// 默认为 "file:src/main/webapp"
@WebAppConfiguration
// 检测同一包中的 "WacTests-context.xml"
// 或静态嵌套 @Configuration 类
@ContextConfiguration
class WacTests {
//...
}
如果在测试类上使用 @WebAppConfiguration 而未指定资源基础路径,
则资源路径默认等同于 file:src/main/webapp。同样,如果声明 @ContextConfiguration
时未指定资源 locations、组件 classes 或上下文 initializers,
Infra 会通过约定来尝试检测你的配置
(即与 WacTests 类同包的 WacTests-context.xml 或静态嵌套的 @Configuration 类)。
下面示例展示了如何使用 @WebAppConfiguration 显式声明资源基础路径,
并使用 @ContextConfiguration 指定 XML 资源位置:
-
Default resource semantics
@ExtendWith(InfraExtension.class)
// 文件系统资源
@WebAppConfiguration("webapp")
// 类路径资源
@ContextConfiguration("/spring/test-servlet-config.xml")
class WacTests {
//...
}
需要注意的是,这两个注解的路径语义不同。默认情况下,@WebAppConfiguration
资源路径基于文件系统,而 @ContextConfiguration 资源位置基于 classpath。
下面示例展示了可以通过指定 Infra 资源前缀来覆盖两个注解的默认资源语义:
-
Explicit resource semantics
@ExtendWith(InfraExtension.class)
// 类路径资源
@WebAppConfiguration("classpath:test-web-resources")
// 文件系统资源
@ContextConfiguration("file:src/main/webapp/WEB-INF/servlet-config.xml")
class WacTests {
//...
}
对比本例与上一例中的注释即可看出差异。