对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

@WebAppConfiguration

@WebAppConfiguration 是一个类级别的注解,您可以使用它来声明为集成测试加载的ApplicationContext应当是一个WebApplicationContext。 只要在测试类上存在@WebAppConfiguration,即可确保为该测试加载一个WebApplicationContext,并使用"file:src/main/webapp"的默认值作为 Web 应用程序根目录(即资源基础路径)的路径。资源基础路径在幕后用于创建MockServletContext,它充当测试的WebApplicationContextServletContextspring-doc.cadn.net.cn

以下示例展示了如何使用 @WebAppConfiguration 注解:spring-doc.cadn.net.cn

@ContextConfiguration
@WebAppConfiguration (1)
class WebAppTests {
	// class body...
}
1 @Repository注解。
@ContextConfiguration
@WebAppConfiguration (1)
class WebAppTests {
	// class body...
}
1 @Repository注解。

要覆盖默认设置,您可以使用隐式的 value 属性来指定不同的基础资源路径。classpath:file: 两种资源前缀均受支持。如果未提供资源前缀,则该路径将被视为文件系统资源。以下示例展示了如何指定一个类路径资源:spring-doc.cadn.net.cn

@ContextConfiguration
@WebAppConfiguration("classpath:test-web-resources") (1)
class WebAppTests {
	// class body...
}
1 指定一个类路径资源。
@ContextConfiguration
@WebAppConfiguration("classpath:test-web-resources") (1)
class WebAppTests {
	// class body...
}
1 指定一个类路径资源。

请注意,@WebAppConfiguration 必须与 @ContextConfiguration 结合使用,可以在单个测试类中,也可以在测试类层次结构中使用。有关更多详细信息,请参阅 @WebAppConfiguration 的 javadoc。spring-doc.cadn.net.cn