关键抽象

框架的核心由TestContextManager类和TestContextTestExecutionListenerSmartContextLoader接口组成。为每个测试类创建一个TestContextManager(例如,在JUnit Jupiter中执行单个测试类中的所有测试方法)。TestContextManager管理一个持有当前测试上下文的TestContextTestContextManager还会随着测试的进行更新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配置

上下文加载器

ContextLoader是一个策略接口,用于为由Spring TestContext Framework管理的集成测试加载ApplicationContext。您应该实现SmartContextLoader而不是这个接口,以提供对组件类、活动bean定义配置文件、测试属性源、上下文层次结构和WebApplicationContext支持。

SmartContextLoaderContextLoader接口的扩展,取代了原始的最小ContextLoader SPI。具体而言,SmartContextLoader可以选择处理资源位置、组件类或上下文初始化器。此外,SmartContextLoader可以在加载的上下文中设置活动bean定义配置文件和测试属性源。

Spring提供以下实现:

  • DelegatingSmartContextLoader:两个默认加载器之一,内部委托给AnnotationConfigContextLoaderGenericXmlContextLoaderGenericGroovyXmlContextLoader,具体取决于为测试类声明的配置或默认位置或默认配置类的存在。仅当Groovy在类路径上时才启用Groovy支持。

  • WebDelegatingSmartContextLoader:两个默认加载器之一,内部委托给AnnotationConfigWebContextLoaderGenericXmlWebContextLoaderGenericGroovyXmlWebContextLoader,具体取决于为测试类声明的配置或默认位置或默认配置类的存在。仅当测试类上存在@WebAppConfiguration时才使用Web ContextLoader。仅当Groovy在类路径上时才启用Groovy支持。

  • AnnotationConfigContextLoader:从组件类加载标准ApplicationContext

  • AnnotationConfigWebContextLoader:从组件类加载WebApplicationContext

  • GenericGroovyXmlContextLoader:从Groovy脚本或XML配置文件加载标准ApplicationContext

  • GenericGroovyXmlWebContextLoader:从Groovy脚本或XML配置文件加载WebApplicationContext

  • GenericXmlContextLoader:从XML资源位置加载标准ApplicationContext

  • GenericXmlWebContextLoader:从XML资源位置加载WebApplicationContext