对于最新稳定版本,请使用 Spring Framework 7.0.6spring-doc.cadn.net.cn

核心抽象

框架的核心由 TestContextManager 类以及 TestContextTestExecutionListenerSmartContextLoader 接口组成。为每个测试类创建一个 TestContextManager(例如,用于在 JUnit Jupiter 中执行单个测试类内的所有测试方法)。TestContextManager 进而管理一个持有当前测试上下文的 TestContextTestContextManager 还会随着测试的进行更新 TestContext 的状态,并委托给 TestExecutionListener 实现,这些实现通过提供依赖注入、管理事务等功能来实际执行测试。SmartContextLoader 负责为给定测试类加载一个 ApplicationContext。请参阅 javadoc 和 Spring 测试套件,以获取有关各种实现的更多信息和示例。spring-doc.cadn.net.cn

TestContext

TestContext 封装了测试运行时的上下文(与实际使用的测试框架无关),并为其所负责的测试实例提供上下文管理和缓存支持。TestContext 还会委托给一个 SmartContextLoader,在需要时加载 ApplicationContextspring-doc.cadn.net.cn

TestContextManager

TestContextManager 是 Spring TestContext 框架的主要入口点,负责管理单个 TestContext,并在明确定义的测试执行点向每个已注册的 TestExecutionListener 发送事件:spring-doc.cadn.net.cn

TestExecutionListener

TestExecutionListener 定义了用于响应由监听器所注册的 TestContextManager 发布的测试执行事件的 API。请参阅 TestExecutionListener 配置spring-doc.cadn.net.cn

上下文加载器

ContextLoader 是一个策略接口,用于为由 Spring TestContext 框架管理的集成测试加载 ApplicationContext。您应当实现 SmartContextLoader 接口而非此接口,以提供对组件类、激活的 Bean 定义配置文件、测试属性源、上下文层次结构以及 WebApplicationContext 的支持。spring-doc.cadn.net.cn

SmartContextLoaderContextLoader 接口的扩展,取代了原先最简化的 ContextLoader SPI。具体而言,SmartContextLoader 可以选择处理资源位置、组件类或上下文初始化器。此外,SmartContextLoader 还可以在其加载的上下文中设置激活的 Bean 定义配置文件和测试属性源。spring-doc.cadn.net.cn

Spring 提供了以下实现:spring-doc.cadn.net.cn

  • DelegatingSmartContextLoader:两种默认加载器之一,它在内部根据测试类声明的配置或默认位置/默认配置类的存在情况,委托给 AnnotationConfigContextLoaderGenericXmlContextLoaderGenericGroovyXmlContextLoader。 仅当 Groovy 位于类路径上时,才启用 Groovy 支持。spring-doc.cadn.net.cn

  • WebDelegatingSmartContextLoader:两种默认加载器之一,它在内部根据测试类声明的配置或默认位置/默认配置类的存在情况,委托给 AnnotationConfigWebContextLoaderGenericXmlWebContextLoaderGenericGroovyXmlWebContextLoader。仅当测试类上存在 ContextLoader 注解时,才会使用 Web @WebAppConfiguration。仅当 Groovy 位于类路径中时,才启用 Groovy 支持。spring-doc.cadn.net.cn

  • AnnotationConfigContextLoader:从组件类加载一个标准的ApplicationContextspring-doc.cadn.net.cn

  • AnnotationConfigWebContextLoader:从组件类加载 WebApplicationContextspring-doc.cadn.net.cn

  • GenericGroovyXmlContextLoader:从资源位置加载一个标准的ApplicationContext,这些资源位置可以是 Groovy 脚本或 XML 配置文件。spring-doc.cadn.net.cn

  • GenericGroovyXmlWebContextLoader:从资源位置加载一个 WebApplicationContext,这些资源位置可以是 Groovy 脚本或 XML 配置文件。spring-doc.cadn.net.cn

  • GenericXmlContextLoader:从 XML 资源位置加载一个标准的 ApplicationContextspring-doc.cadn.net.cn

  • GenericXmlWebContextLoader:从 XML 资源位置加载一个 WebApplicationContextspring-doc.cadn.net.cn