|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
核心抽象概念
框架的核心由TestContextManager类以及TestContext、TestExecutionListener和SmartContextLoader接口组成。为每个测试类(例如,在JUnit Jupiter中执行单个测试类内的所有测试方法)创建TestContextManager。TestContextManager则管理着一个保存当前测试上下文的TestContext。TestContextManager会随着测试进度更新TestContext的状态,并委托给TestExecutionListener实现,这些实现通过提供依赖注入、管理事务等方式实际执行测试操作。SmartContextLoader负责为给定测试类加载ApplicationContext。有关各种实现的更多信息和示例,请参阅javadoc和Spring测试套件。
TestContext
TestContext 封装了运行测试的上下文(独立于实际使用的测试框架),并为所负责的测试实例提供上下文管理和缓存支持。TestContext 还会委托 SmartContextLoader 在请求时加载 ApplicationContext。
TestContextManager
TestContextManager 是 Spring TestContext 框架的主要入口点,负责管理单个 TestContext 并向每个已注册的 TestExecutionListener 在明确定义的测试执行点发出信号事件:
-
在任何特定测试框架的“类之前”或“所有之前”方法执行之前。
-
测试实例后处理。
-
在特定测试框架的任何'前置'或'每个前置'方法之前。
-
在测试方法执行之前紧接,但在测试设置之后。
-
测试方法执行之后立即执行,但在测试拆卸之前。
-
在特定测试框架的任何'after'或'after each'方法之后。
-
在特定测试框架的任何“类之后”或“所有之后”方法之后。
TestExecutionListener
TestExecutionListener 定义了用于响应由 TestContextManager 发布的测试执行事件的 API,监听器与之注册。参见 TestExecutionListener 配置。
上下文加载器
ContextLoader 是 Spring TestContext 框架用于加载集成测试所需 ApplicationContext 的策略接口。您应当实现 SmartContextLoader 而非此接口,以提供对组件类、活动 bean 定义配置文件、测试属性源、上下文层次结构以及 WebApplicationContext 的支持。
SmartContextLoader 是 ContextLoader 接口的扩展,它取代了原始的最小 ContextLoader SPI。具体来说,一个 SmartContextLoader 可以选择处理资源位置、组件类或上下文初始化器。此外,一个 SmartContextLoader 可以在它加载的上下文中设置活动的bean定义配置文件和测试属性源。
Spring 提供以下实现:
-
DelegatingSmartContextLoader:两个默认加载器之一,它根据测试类声明的配置或默认位置/默认配置类的存在情况, 内部委托给AnnotationConfigContextLoader、GenericXmlContextLoader或GenericGroovyXmlContextLoader实现。 仅当类路径中存在Groovy时才会启用Groovy支持。 -
WebDelegatingSmartContextLoader: 两个默认加载器之一,它会根据测试类声明的配置或默认位置/默认配置类的存在情况,在内部委托给AnnotationConfigWebContextLoader、GenericXmlWebContextLoader或GenericGroovyXmlWebContextLoader。仅当测试类上存在@WebAppConfiguration时才会使用WebContextLoader。仅当类路径中存在Groovy时才会启用Groovy支持。 -
AnnotationConfigContextLoader: 从组件类加载标准ApplicationContext配置。 -
AnnotationConfigWebContextLoader: 从组件类加载WebApplicationContext。 -
GenericGroovyXmlContextLoader: 从资源位置加载标准ApplicationContext,资源位置可以是Groovy脚本或XML配置文件。 -
GenericGroovyXmlWebContextLoader: 从资源位置加载一个WebApplicationContext,这些资源位置可以是Groovy脚本或XML配置文件。 -
GenericXmlContextLoader: 从XML资源位置加载标准的ApplicationContext。 -
GenericXmlWebContextLoader: 从XML资源位置加载一个WebApplicationContext