此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
加载一个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
,您可以自由声明 XML 配置文件、Groovy 脚本、 或@Configuration
类,使用@ContextConfiguration
. 您也可以免费使用任何其他测试注释,例如@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
如果不指定资源base 路径,则资源路径实际上默认为file:src/main/webapp
. 同样地 如果您声明@ContextConfiguration
不指定资源locations
元件classes
或上下文initializers
,Spring 会尝试使用约定(即WacTests-context.xml
在同一个包中作为WacTests
类或静态嵌套@Configuration
类)。
以下示例演示如何使用@WebAppConfiguration
以及 XML 资源位置@ContextConfiguration
:
-
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 {
//...
}
将此示例中的注释与前面的示例进行对比。