|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
测试执行事件
Spring Framework 5.2 引入的 EventPublishingTestExecutionListener 提供了一种实现自定义 TestExecutionListener 的替代方案。测试中的 ApplicationContext 组件可以监听 EventPublishingTestExecutionListener 发布的以下事件,每个事件对应 TestExecutionListener API 中的一个方法。
-
BeforeTestClassEvent -
PrepareTestInstanceEvent -
BeforeTestMethodEvent -
BeforeTestExecutionEvent -
AfterTestExecutionEvent -
AfterTestMethodEvent -
AfterTestClassEvent
这些事件可以被消费用于多种目的,例如重置模拟bean或追踪测试执行。消费测试执行事件相较于实现自定义TestExecutionListener的一个优势在于:测试执行事件可由注册在测试ApplicationContext中的任何Spring bean消费,且这些bean能直接受益于ApplicationContext的依赖注入及其他特性。相对地,TestExecutionListener并非ApplicationContext中的bean。
|
默认情况下, 因此, 如果您希望确保每个测试类都始终发布一个 同样,如果在给定测试类的最后一个测试方法后使用 |
为了监听测试执行事件,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文档。