@WebAppConfiguration

@WebAppConfiguration 是一个注释,可以应用到测试类中,声明在集成测试中加载的 ApplicationContext 应该为 WebApplicationContext。在测试类中使用 @WebAppConfiguration 可确保为测试加载 WebApplicationContext,使用默认路径 "file:src/main/webapp" 作为 Web 应用程序的根目录(即资源基础路径)。资源基础路径在后台用于创建 MockServletContext,它作为测试的 WebApplicationContextServletContext

@WebAppConfiguration is an annotation that can be applied to a test class to declare that the ApplicationContext loaded for an integration test should be a WebApplicationContext. The mere presence of @WebAppConfiguration on a test class ensures that a WebApplicationContext is loaded for the test, using the default value of "file:src/main/webapp" for the path to the root of the web application (that is, the resource base path). The resource base path is used behind the scenes to create a MockServletContext, which serves as the ServletContext for the test’s WebApplicationContext.

以下示例演示了如何使用 @WebAppConfiguration 注释:

The following example shows how to use the @WebAppConfiguration annotation:

Java
@ContextConfiguration
@WebAppConfiguration (1)
class WebAppTests {
	// class body...
}
1 The @WebAppConfiguration annotation.
Kotlin
@ContextConfiguration
@WebAppConfiguration (1)
class WebAppTests {
	// class body...
}
2 The @WebAppConfiguration annotation.

要覆盖默认值,可以使用隐式 value 属性指定不同的基础资源路径。支持 classpath:file: 资源前缀。如果未提供资源前缀,路径将假定为文件系统资源。以下示例演示了如何指定 classpath 资源:

To override the default, you can specify a different base resource path by using the implicit value attribute. Both classpath: and file: resource prefixes are supported. If no resource prefix is supplied, the path is assumed to be a file system resource. The following example shows how to specify a classpath resource:

Java
@ContextConfiguration
@WebAppConfiguration("classpath:test-web-resources") (1)
class WebAppTests {
	// class body...
}
1 Specifying a classpath resource.
Kotlin
@ContextConfiguration
@WebAppConfiguration("classpath:test-web-resources") (1)
class WebAppTests {
	// class body...
}
2 Specifying a classpath resource.

请注意,@WebAppConfiguration`必须与 `@ContextConfiguration`结合使用,它们位于一个测试类或一个测试类层次结构中。请参阅https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/context/web/WebAppConfiguration.html[@WebAppConfiguration`]javadoc 了解更多详情。

Note that @WebAppConfiguration must be used in conjunction with @ContextConfiguration, either within a single test class or within a test class hierarchy. See the @WebAppConfiguration javadoc for further details.