|
对于最新稳定版本,请使用Spring Framework 7.0.1! |
加载 aWebApplicationContext
指示TestContext框架加载WebApplicationContext而不是
标准应用上下文你可以对相应的测试类进行注释,用@WebAppConfiguration.
存在@WebAppConfiguration在你的测试类中指示TestContext
框架(TCF)中 aWebApplicationContext(WAC)应该已经装填好了,供你们使用
积分测试。在幕后,TCF确保模拟服务器上下文是
创建并提供给你测试的WAC。默认情况下,你的基础资源路径模拟服务器上下文设置为src/main/webapp.这被解释为路径相对关系
回到你 JVM 的根节点(通常是通往项目的路径)。如果你熟悉
在Maven项目中,网页应用的目录结构,你知道的src/main/webapp是你战争根源的默认位置。如果你需要的话
覆盖这个默认设置,你可以提供一条替代路径@WebAppConfiguration注释(例如,@WebAppConfiguration(“src/test/webapp”)).如果你愿意的话
你可以用类路径中的基础资源路径来引用,而不是文件系统
斯普林斯Classpath:前缀。
注意 Spring 的测试支持WebApplicationContext实现水平相当
并支持标准应用上下文实现。在测试时WebApplicationContext你可以自由声明XML配置文件、Groovy脚本,
或@Configuration通过使用@ContextConfiguration.你也可以自由使用
任何其他测试注释,例如@ActiveProfiles,@TestExecutionListeners,@Sql,@Rollback,以及其他。
本节剩余的示例展示了以下几种配置选项
加载WebApplicationContext.以下示例展示了TestContext
Framework 对惯例优先配置的支持:
-
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但未指定资源
基础路径,资源路径实际上默认为文件:src/main/webapp.同样地
如果你宣告@ContextConfiguration但未指定资源地点元件类,或上下文初始化器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 {
//...
}
将这个例子中的评论与之前的例子对比一下。