测试执行事件
EventPublishingTestExecutionListener
提供了一种实现自定义 TestExecutionListener
的替代方法。测试的 ApplicationContext
中的组件可以监听由 EventPublishingTestExecutionListener
发布的以下事件,每个事件都对应于 TestExecutionListener
API 中的方法。
-
BeforeTestClassEvent
-
PrepareTestInstanceEvent
-
BeforeTestMethodEvent
-
BeforeTestExecutionEvent
-
AfterTestExecutionEvent
-
AfterTestMethodEvent
-
AfterTestClassEvent
这些事件可能会因为各种原因被消费,例如重置模拟 bean 或跟踪测试执行。消费测试执行事件的一个优势是,测试执行事件可以被注册在测试 ApplicationContext
中的任何 Spring bean 所消费,这样的 bean 可以直接受益于依赖注入和 ApplicationContext
的其他特性。相比之下,TestExecutionListener
不是 ApplicationContext
中的一个 bean。
EventPublishingTestExecutionListener
默认是注册的;然而,它只有在 ApplicationContext
已经被加载的情况下才会发布事件。这可以防止 ApplicationContext
被不必要地或过早地加载。
因此,BeforeTestClassEvent
不会在 ApplicationContext
被其他 TestExecutionListener
加载之前发布。例如,在默认注册的一组 TestExecutionListener
实现中,使用特定测试 ApplicationContext
的第一个测试类不会发布 BeforeTestClassEvent
,但在同一测试套件中使用相同测试 ApplicationContext
的任何后续测试类将会发布 BeforeTestClassEvent
,因为在后续测试类运行时上下文已经被加载(只要上下文没有通过 @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。