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