关键抽象
该框架的核心由 TestContextManager
类以及 TestContext
、TestExecutionListener
和 SmartContextLoader
接口组成。每个测试类(例如,在 JUnit Jupiter 中执行单个测试类中的所有测试方法)都会创建一个 TestContextManager
。TestContextManager
负责管理一个 TestContext
,该 TestContext
持有当前测试的上下文。随着测试的进行,TestContextManager
还会更新 TestContext
的状态,并委托给 TestExecutionListener
实现,这些实现通过提供依赖注入、管理事务等方式来辅助实际的测试执行。SmartContextLoader
负责为给定的测试类加载一个 ApplicationContext
。有关更多信息和各种实现的示例,请参见 javadoc 和 Spring 测试套件。
TestContext
TestContext
封装了测试运行的上下文(与实际使用的测试框架无关),并为其负责的测试实例提供上下文管理和缓存支持。TestContext
还委托给 SmartContextLoader
以在需要时加载 ApplicationContext
。
TestContextManager
TestContextManager
是 Spring TestContext 框架的主要入口,负责管理单个 TestContext
并在定义良好的测试执行点向每个注册的 TestExecutionListener
发出事件信号:
-
在特定测试框架的任何“类前”或“全局前”方法之前。
-
测试实例后处理。
-
在特定测试框架的任何“前”或“每次前”方法之前。
-
在测试方法执行之前但在测试设置之后立即执行。
-
在测试方法执行之后但在测试拆解之前立即执行。
-
在特定测试框架的任何“后”或“每次后”方法之后。
-
在特定测试框架的任何“类后”或“全局后”方法之后。
TestExecutionListener
TestExecutionListener
定义了用于响应由注册了该监听器的 TestContextManager
发布的测试执行事件的 API。请参阅TestExecutionListener 配置。
上下文加载器
ContextLoader
是一个策略接口,用于加载由 Spring TestContext Framework 管理的集成测试的 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
。