跳到主要内容

加载 WebApplicationContext

DeepSeek V3 中英对照 Loading a WebApplicationContext Loading a 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 进行测试时,你可以自由地通过 @ContextConfiguration 声明 XML 配置文件、Groovy 脚本或 @Configuration 类。你还可以自由使用任何其他测试注解,例如 @ActiveProfiles@TestExecutionListeners@Sql@Rollback 等。

本节中的其余示例展示了加载 WebApplicationContext 的各种配置选项。以下示例展示了 TestContext 框架对约定优于配置的支持:

@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 {
//...
}
java

如果你在测试类上使用 @WebAppConfiguration 注解而不指定资源基础路径,资源路径实际上会默认设置为 file:src/main/webapp。同样,如果你声明 @ContextConfiguration 而不指定资源 locations、组件 classes 或上下文 initializers,Spring 会尝试通过约定来检测你的配置是否存在(即在与 WacTests 类相同的包中的 WacTests-context.xml 文件或静态嵌套的 @Configuration 类)。

以下示例展示了如何使用 @WebAppConfiguration 显式声明资源基础路径,以及使用 @ContextConfiguration 声明 XML 资源位置:

@ExtendWith(SpringExtension.class)

// file system resource
@WebAppConfiguration("webapp")

// classpath resource
@ContextConfiguration("/spring/test-servlet-config.xml")
class WacTests {
//...
}
java

这里需要注意的重要一点是,带有这两种注解的路径具有不同的语义。默认情况下,@WebAppConfiguration 的资源路径是基于文件系统的,而 @ContextConfiguration 的资源位置是基于类路径的。

以下示例展示了我们可以通过指定 Spring 资源前缀来覆盖两个注解的默认资源语义:

@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 {
//...
}
java

将这个示例中的注释与前一个示例进行对比。