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

核心抽象概念

框架的核心由TestContextManager类以及TestContextTestExecutionListenerSmartContextLoader接口组成。为每个测试类(例如,在JUnit Jupiter中执行单个测试类内的所有测试方法)创建TestContextManagerTestContextManager则管理着一个保存当前测试上下文的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。仅当测试类上存在@WebAppConfiguration时才会使用WebContextLoader。仅当类路径中存在Groovy时才会启用Groovy支持。spring-doc.cadn.net.cn

  • AnnotationConfigContextLoader: 从组件类加载标准ApplicationContext配置。spring-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