|
对于最新稳定版本,请使用 Spring Framework 7.0.6! |
测试执行事件
Spring Framework 5.2 引入的 EventPublishingTestExecutionListener 提供了一种实现自定义 TestExecutionListener 的替代方法。测试的 ApplicationContext 中的组件可以监听由 EventPublishingTestExecutionListener 发布的以下事件,每个事件分别对应于 TestExecutionListener API 中的一个方法。
-
BeforeTestClassEvent -
PrepareTestInstanceEvent -
BeforeTestMethodEvent -
BeforeTestExecutionEvent -
AfterTestExecutionEvent -
AfterTestMethodEvent -
AfterTestClassEvent
这些事件可能会出于各种原因被消费,例如重置模拟(mock)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。