加载 WebApplicationContext
要指示 TestContext 框架加载 WebApplicationContext
而不是标准的 ApplicationContext
,你可以使用 @WebAppConfiguration
注解相应的测试类。
在你的测试类上存在 @WebAppConfiguration
注解指示 TestContext 框架 (TCF) 为你的集成测试加载 WebApplicationContext
(WAC)。在后台,TCF 会确保创建一个 MockServletContext
并将其提供给你的测试 WAC。默认情况下,你的 MockServletContext
的基本资源路径被设置为 src/main/webapp
。这被解释为相对于 JVM 根目录(通常是你的项目路径)的路径。如果你熟悉 Maven 项目中 Web 应用程序的目录结构,你会知道 src/main/webapp
是 WAR 根目录的默认位置。如果你需要覆盖此默认设置,可以为 @WebAppConfiguration
注解提供备用路径(例如,@WebAppConfiguration("src/test/webapp")
)。如果你希望引用类路径而不是文件系统中的基本资源路径,可以使用 Spring 的 classpath:
前缀。
请注意,Spring 对 WebApplicationContext
实现的测试支持与对标准 ApplicationContext
实现的支持是一致的。使用 WebApplicationContext
进行测试时,你可以使用 @ContextConfiguration
声明 XML 配置文件、Groovy 脚本或 @Configuration
类。你也可以自由使用任何其他测试注解,例如 @ActiveProfiles
、@TestExecutionListeners
、@Sql
、@Rollback
等。
本节的其余示例展示了加载 WebApplicationContext
的一些各种配置选项。以下示例展示了 TestContext 框架对约定优于配置的支持
-
Java
-
Kotlin
@ExtendWith(SpringExtension.class)
// defaults to "file:src/main/webapp"
@WebAppConfiguration
// detects "WacTests-context.xml" in the same package
// or static nested @Configuration classes
@ContextConfiguration
class WacTests {
//...
}
@ExtendWith(SpringExtension::class)
// defaults to "file:src/main/webapp"
@WebAppConfiguration
// detects "WacTests-context.xml" in the same package
// or static nested @Configuration classes
@ContextConfiguration
class WacTests {
//...
}
如果你在测试类上使用 @WebAppConfiguration
注解但未指定资源基本路径,则资源路径实际上默认为 file:src/main/webapp
。类似地,如果你声明 @ContextConfiguration
但未指定资源 locations
、组件 classes
或上下文 initializers
,Spring 会尝试使用约定来检测你的配置是否存在(即,与 WacTests
类在同一包中的 WacTests-context.xml
或静态嵌套的 @Configuration
类)。
以下示例展示了如何使用 @WebAppConfiguration
显式声明资源基本路径,并使用 @ContextConfiguration
显式声明 XML 资源位置
-
Java
-
Kotlin
@ExtendWith(SpringExtension.class)
// file system resource
@WebAppConfiguration("webapp")
// classpath resource
@ContextConfiguration("/spring/test-servlet-config.xml")
class WacTests {
//...
}
@ExtendWith(SpringExtension::class)
// file system resource
@WebAppConfiguration("webapp")
// classpath resource
@ContextConfiguration("/spring/test-servlet-config.xml")
class WacTests {
//...
}
这里需要注意的重要一点是这两个注解路径的语义不同。默认情况下,@WebAppConfiguration
资源路径基于文件系统,而 @ContextConfiguration
资源位置基于类路径。
以下示例显示,通过指定 Spring 资源前缀,我们可以覆盖这两个注解的默认资源语义
-
Java
-
Kotlin
@ExtendWith(SpringExtension.class)
// classpath resource
@WebAppConfiguration("classpath:test-web-resources")
// file system resource
@ContextConfiguration("file:src/main/webapp/WEB-INF/servlet-config.xml")
class WacTests {
//...
}
@ExtendWith(SpringExtension::class)
// classpath resource
@WebAppConfiguration("classpath:test-web-resources")
// file system resource
@ContextConfiguration("file:src/main/webapp/WEB-INF/servlet-config.xml")
class WacTests {
//...
}
对比此示例与前一个示例中的注释。