加载 GenericWebApplicationContext

要让 TestContext 框架加载 GenericMockWebApplicationContext 而不是标准的 ApplicationContext, 可以在相应测试类上标注 @WebAppConfiguration

在测试类上使用 @WebAppConfiguration 会指示 TestContext 框架(TCF)为你的集成测试加载 GenericMockWebApplicationContext(WAC)。

请注意,Infra 对 GenericMockWebApplicationContext 实现的测试支持与对标准 ApplicationContext 实现的支持一致。使用 GenericMockWebApplicationContext 测试时,你可以通过 @ContextConfiguration 声明 XML 配置文件、Groovy 脚本或 @Configuration 类。 也可以使用其他测试注解,例如 @ActiveProfiles@TestExecutionListeners@Sql@Rollback 等。

本节剩余示例展示了加载 GenericMockWebApplicationContext 的多种配置选项。 下面示例展示了 TestContext 框架对“约定优于配置”的支持:

  • Conventions

@ExtendWith(InfraExtension.class)

@WebAppConfiguration

// 检测同一包中的 "WacTests-context.xml"
// 或静态嵌套 @Configuration 类
@ContextConfiguration
class WacTests {
  //...
}

如果在测试类上使用 @WebAppConfiguration 而未指定资源基础路径, 则资源路径默认等同于 file:src/main/webapp。同样,如果声明 @ContextConfiguration 时未指定资源 locations、组件 classes 或上下文 initializers, Infra 会通过约定来尝试检测你的配置 (即与 WacTests 类同包的 WacTests-context.xml 或静态嵌套的 @Configuration 类)。

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

  • Default resource semantics

@ExtendWith(InfraExtension.class)

// 文件系统资源
@WebAppConfiguration

// 类路径资源
@ContextConfiguration("/config/test-config-config.xml")
class WacTests {
  //...
}

需要注意的是,这两个注解的路径语义不同。默认情况下,@WebAppConfiguration 资源路径基于文件系统,而 @ContextConfiguration 资源位置基于 classpath。

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

  • Explicit resource semantics

@ExtendWith(InfraExtension.class)

@WebAppConfiguration

// 文件系统资源
@ContextConfiguration("file:src/main/webapp/WEB-INF/config-config.xml")
class WacTests {
  //...
}

对比本例与上一例中的注释即可看出差异。