加载 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 {
//...
}
请将此示例中的注释与上一个示例进行对比。