此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0spring-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")).如果您愿意 从 Classpath 而不是文件系统中引用基本资源路径,您可以使用 Spring的classpath:前缀。spring-doc.cadn.net.cn

请注意,Spring 对WebApplicationContextimplementations 相当 支持标准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 path 时,资源路径实际上默认为file:src/main/webapp.同样地 如果您声明@ContextConfiguration不指定 resourcelocations元件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 {
	//...
}

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

下面的示例显示,我们可以覆盖两者的默认资源语义 注解: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