测试执行事件
EventPublishingTestExecutionListener 提供了一种实现自定义 TestExecutionListener 的替代方法。测试中的 ApplicationContext 内的组件可以监听 EventPublishingTestExecutionListener 发布的以下事件,每个事件都对应于 TestExecutionListener API 中的一个方法。
-
BeforeTestClassEvent -
PrepareTestInstanceEvent -
BeforeTestMethodEvent -
BeforeTestExecutionEvent -
AfterTestExecutionEvent -
AfterTestMethodEvent -
AfterTestClassEvent
这些事件可能因各种原因而被消费,例如重置模拟bean或跟踪测试执行。与实现自定义的TestExecutionListener相比,消费测试执行事件的一个优势是,任何在测试ApplicationContext中注册的Spring bean都可以消费测试执行事件,这样的bean可以直接从依赖注入和ApplicationContext的其他特性中受益。相比之下,TestExecutionListener并不是ApplicationContext中的bean。
EventPublishingTestExecutionListener 默认是注册好的;但是,它只有在 ApplicationContext 已经加载完成 时才会发布事件。这样可以防止 ApplicationContext 被不必要的或过早地加载。
因此,在另一个 TestExecutionListener 加载完 ApplicationContext 之前,BeforeTestClassEvent 是不会被发布的。例如,在默认注册的 TestExecutionListener 实现中,对于第一个使用某个 ApplicationContext 的测试类,BeforeTestClassEvent 不会被发布;但对于同一测试套件中后续使用相同 ApplicationContext 的测试类,BeforeTestClassEvent 会 被发布,因为当后续测试类运行时,ApplicationContext 已经被加载好了(只要该 ApplicationContext 没有通过 @DirtiesContext 或最大容量淘汰策略从 ContextCache 中移除)。
如果你希望确保每个测试类都能触发 BeforeTestClassEvent,那么你需要注册一个在 beforeTestClass 回调中加载 ApplicationContext 的 TestExecutionListener,并且这个 TestExecutionListener 必须在 EventPublishingTestExecutionListener 之前注册。
同样地,如果使用 @DirtiesContext 在某个测试类的最后一个测试方法之后将 ApplicationContext 从上下文缓存中移除,那么该测试类的 AfterTestClassEvent 就不会被发布了。
为了监听测试执行事件,一个Spring bean可以选择实现org.springframework.context.ApplicationListener接口。或者,也可以使用@EventListener注解来标注监听方法,并配置这些方法以监听上述列出的特定事件类型之一(参见基于注解的事件监听器)。由于这种方法的流行性,Spring提供了以下专门的@EventListener注解来简化测试执行事件监听器的注册过程。这些注解位于org.springframework.test.context.event.annotation包中。
-
@BeforeTestClass -
@PrepareTestInstance -
@BeforeTestMethod -
@BeforeTestExecution -
@AfterTestExecution -
@AfterTestMethod -
@AfterTestClass
异常处理
默认情况下,如果在消费事件时测试执行事件监听器抛出异常,该异常将传播到所使用的底层测试框架(如JUnit或TestNG)。例如,如果消费BeforeTestMethodEvent时引发异常,相应的测试方法将因该异常而失败。相比之下,如果异步测试执行事件监听器抛出异常,该异常不会传播到底层测试框架。有关异步异常处理的更多详细信息,请参阅@EventListener的类级javadoc。
异步监听器
如果你希望某个特定的测试执行事件监听器能够异步处理事件,你可以使用Spring的常规@Async支持。有关更多详细信息,请查阅@EventListener的类级Javadoc。