|
对于最新的稳定版本,请使用 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
框架对约定胜过配置的支持:
-
Conventions
-
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:
-
Default resource semantics
-
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 资源前缀来注释:
-
Explicit resource semantics
-
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 {
//...
}
将此示例中的注释与前面的示例进行对比。