此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10spring-doc.cadn.net.cn

加载一个WebApplicationContext

要指示 TestContext 框架加载WebApplicationContext而不是 标准ApplicationContext,您可以使用@WebAppConfiguration.spring-doc.cadn.net.cn

的存在@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-doc.cadn.net.cn

请注意,Spring 对WebApplicationContext实现与对标准的支持不相上下它对标准的支持ApplicationContext实现。 使用WebApplicationContext,您可以自由声明 XML 配置文件、Groovy 脚本、 或@Configuration类,使用@ContextConfiguration. 您也可以免费使用任何其他测试注释,例如@ActiveProfiles,@TestExecutionListeners,@Sql,@Rollback,等。spring-doc.cadn.net.cn

本节中的其余示例显示了一些正在加载一个WebApplicationContext. 以下示例显示了 TestContext框架对约定而不是配置的支持:spring-doc.cadn.net.cn

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

如果使用@WebAppConfiguration如果不指定资源base 路径,则资源路径实际上默认为file:src/main/webapp. 同样地 如果您声明@ContextConfiguration不指定资源locations元件classes或上下文initializers,Spring 会尝试使用约定(即WacTests-context.xml在同一个包中作为WacTests类或静态嵌套@Configuration类)。spring-doc.cadn.net.cn

以下示例演示如何使用@WebAppConfiguration以及 XML 资源位置@ContextConfiguration:spring-doc.cadn.net.cn

默认资源语义
@ExtendWith(SpringExtension.class)

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

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

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

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

这里需要注意的重要一点是,这两个路径的不同语义 附注。 默认情况下,@WebAppConfiguration资源路径是基于文件系统的, 而@ContextConfiguration资源位置基于类路径。spring-doc.cadn.net.cn

以下示例表明,我们可以覆盖两个注释的默认资源语义,方法是指定 Spring 资源前缀:spring-doc.cadn.net.cn

显式资源语义
@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 {
	//...
}
@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 {
	//...
}

将此示例中的注释与前面的示例进行对比。spring-doc.cadn.net.cn