对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
关键抽象
框架的核心包括TestContextManager
类和TestContext
,TestExecutionListener
和SmartContextLoader
接口。一个TestContextManager
为每个测试类创建(例如,为了执行
JUnit Jupiter 中单个测试类中的所有测试方法)。这TestContextManager
,
反过来,管理TestContext
,它保存当前测试的上下文。这TestContextManager
还会更新TestContext
随着测试的进行
和委托人TestExecutionListener
实现,这些实现将实际的
通过提供依赖项注入、管理事务等来测试执行。一个SmartContextLoader
负责加载ApplicationContext
对于给定的测试
类。请参阅 javadoc 和
Spring test 套件,以获取更多信息和各种实现的示例。
TestContext
TestContext
封装运行测试的上下文(与
实际测试框架),并为
它负责的 test 实例。这TestContext
还会委托给SmartContextLoader
要加载ApplicationContext
如果需要。
TestContextManager
TestContextManager
是 Spring TestContext 框架的主要入口点,并且是
负责管理单个TestContext
并向每个已注册的TestExecutionListener
在定义明确的测试执行点:
-
在特定测试框架的任何 “before class” 或 “before all” 方法之前。
-
测试实例后处理。
-
在特定测试框架的任何 “before” 或 “before each” 方法之前。
-
在执行测试方法之前,但在测试设置之后。
-
在执行测试方法之后但在测试拆除之前立即。
-
在特定测试框架的任何 “after” 或 “after each” 方法之后。
-
在特定测试框架的任何 “after class” 或 “after all” 方法之后。
TestExecutionListener
TestExecutionListener
定义用于响应
这TestContextManager
侦听器注册到的 URL。看TestExecutionListener
配置.
上下文加载器
ContextLoader
是一个策略接口,用于加载ApplicationContext
对于
由 Spring TestContext 框架管理的集成测试。您应该实施SmartContextLoader
而不是这个接口来提供对组件类的支持,
活动 Bean 定义配置文件、测试属性源、上下文层次结构和WebApplicationContext
支持。
SmartContextLoader
是ContextLoader
接口,它取代了
原始最小ContextLoader
SPI 的 API 中。具体来说,SmartContextLoader
可以选择
进程资源位置、组件类或上下文初始值设定项。此外,SmartContextLoader
可以在 中设置活动的 Bean 定义配置文件并测试属性源
它加载的上下文。
Spring 提供了以下实现:
-
DelegatingSmartContextLoader
:两个默认加载器之一,它在内部委托给 一AnnotationConfigContextLoader
一个GenericXmlContextLoader
或GenericGroovyXmlContextLoader
,具体取决于为 test 类或是否存在 default locations 或 default configuration 类。 仅当 Groovy 位于 Classpath 上时,才会启用 Groovy 支持。 -
WebDelegatingSmartContextLoader
:两个默认加载器之一,它在内部委托 更改为AnnotationConfigWebContextLoader
一个GenericXmlWebContextLoader
或GenericGroovyXmlWebContextLoader
,具体取决于为 测试类或存在 default locations 或 default configuration 类。一个 webContextLoader
仅在以下情况下使用@WebAppConfiguration
位于 test 类。仅当 Groovy 位于 Classpath 上时,才会启用 Groovy 支持。 -
AnnotationConfigContextLoader
:加载标准ApplicationContext
from 组件 类。 -
AnnotationConfigWebContextLoader
:加载一个WebApplicationContext
from 组件 类。 -
GenericGroovyXmlContextLoader
:加载标准ApplicationContext
从资源 位置,可以是 Groovy 脚本或 XML 配置文件。 -
GenericGroovyXmlWebContextLoader
:加载一个WebApplicationContext
从资源 位置,可以是 Groovy 脚本或 XML 配置文件。 -
GenericXmlContextLoader
:加载标准ApplicationContext
从 XML 资源 地点。 -
GenericXmlWebContextLoader
:加载一个WebApplicationContext
从 XML 资源 地点。