测试执行事件
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。