加载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框架对约定优于配置的支持:

  • 约定

  • Kotlin

@ExtendWith(SpringExtension.class)

// 默认为"file:src/main/webapp"
@WebAppConfiguration

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

// 默认为"file:src/main/webapp"
@WebAppConfiguration

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

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

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

  • 默认资源语义

  • Kotlin

@ExtendWith(SpringExtension.class)

// 文件系统资源
@WebAppConfiguration("webapp")

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

// 文件系统资源
@WebAppConfiguration("webapp")

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

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

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

  • 显式资源语义

  • Kotlin

@ExtendWith(SpringExtension.class)

// 类路径资源
@WebAppConfiguration("classpath:test-web-resources")

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

// 类路径资源
@WebAppConfiguration("classpath:test-web-resources")

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

将此示例中的注释与上一个示例进行对比。