加载一个 WebApplicationContext
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脚本或使用@ContextConfiguration注解的类。你也可以自由地使用其他任何测试注解,如@ActiveProfiles、@TestExecutionListeners、@Sql、@Rollback等。
本节中剩余的示例展示了一些加载WebApplicationContext的各种配置选项。以下示例展示了TestContext框架对“约定优于配置”(convention over configuration)的支持:
- 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注解但没有指定资源位置(resource locations)、组件类(component classes)或上下文初始化器(context 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 {
//...
}
将这个例子中的评论与上一个例子中的评论进行对比。