前言 Spring TestContext Framework的组成
我们已知spring testContext framework由以下几部分组成
- TestContext: 一个测试方法一个TestContext,由TestContextManager管理。
- TestExecutionListener:测试方法或类上常会有一些注解,对其的解析操作交由对应的TestExecutionListener执行,比如事务管理、依赖注入等。
- TestContextManager:一个测试类一个TestContextManager,用于管理TextContext,并触发注册的TextExecutionListener去干活。
- SmartContextLoader:用于加载ApplicationContext,提供对component classes, active bean definition profiles, test property sources, context hierarchies, and WebApplicationContext 的支持
- TestContextBootStrappers:为TestContextManager加载各种TestExecutionListener的实现,并为当前测试方法创建TestContext。
TestExecutionListener的定义与作用
@TestExecutionListener是TestContextFramework下的一个类级别注解,与@ContextConfiguration连用。
它的作用是:
- 在执行测试的声明周期中可以做一些自定义的事情。
- 并将当前测试方法的TestContext暴露出来。
@ContextConfiguration
@TestExecutionListeners({CustomTestExecutionListener.class, AnotherTestExecutionListener.class})
class CustomTestExecutionListenerTests {
// class body...
}
Spring默认提供的TestExecutionListener实现类
翻译自 3.5.3. TestExecutionListener Configuration
- ServletMockExecutionListener 为mock WebApplicationContext提供Servlet相关的API。
- DirtiesContextBeforeModesTestExecutionListener 在before模式中,处理@DirtiesContext注解。
- ApplicationEventTestExecutionListener 用于处理ApplicationEvent。
- DependencyInjectionTestExecutionListener 用于处理依赖注入。
- DirtiesContextTestExecutionListener 用于处理after模式中的@DirtiesContext注解。
- TransactionalTestExecutionListener 用于处理事务注解。
- SqlScriptsTestExecutionListener 用于处理@Sql注解。
- EventPublishingTestExecutionListener 向mock出来的ApplicationContext中增加test execution events。
新增自定义TestExecutionListener
由于公司使用了Spring4,并不具备@Sql注解,所以打算自定义一个。
自定义TestExecutionListener