此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
加载一个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")
).如果您愿意
从 Classpath 而不是文件系统中引用基本资源路径,您可以使用
Spring的classpath:
前缀。
请注意,Spring 对WebApplicationContext
implementations 相当
支持标准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 path 时,资源路径实际上默认为file:src/main/webapp
.同样地
如果您声明@ContextConfiguration
不指定 resourcelocations
元件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 {
//...
}
这里需要注意的重要一点是具有这两个的 paths 的不同语义
附注。默认情况下,@WebAppConfiguration
资源路径基于文件系统,
而@ContextConfiguration
资源位置是基于 Classpath 的。
下面的示例显示,我们可以覆盖两者的默认资源语义 注解:
-
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 {
//...
}
将此示例中的注释与上一个示例进行对比。