此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
测试执行事件
这EventPublishingTestExecutionListener
提供了另一种实施方法
一个习惯TestExecutionListener
.测试中组件ApplicationContext
能
监听以下事件EventPublishingTestExecutionListener
,每个方法对应于TestExecutionListener
应用程序接口。
-
BeforeTestClassEvent
-
PrepareTestInstanceEvent
-
BeforeTestMethodEvent
-
BeforeTestExecutionEvent
-
AfterTestExecutionEvent
-
AfterTestMethodEvent
-
AfterTestClassEvent
这些事件可能出于各种原因被使用,例如重置模拟 Bean 或跟踪
测试执行。使用测试执行事件而不是实现测试执行事件的一个优点
一个习惯TestExecutionListener
测试执行事件可以被任何
在测试中注册的春豆ApplicationContext
,这些Beans可能会受益
直接来自依赖注入和ApplicationContext
.在
对比,一个TestExecutionListener
不是ApplicationContext
.
这 因此,一个 如果您希望确保 同样,如果 |
为了监听测试执行事件,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
结果
异常,相应的测试方法将因异常而失败。在
相反,如果异步测试执行事件监听器抛出异常,则
异常不会传播到底层测试框架。有关
异步异常处理,请参阅类级 Javadoc@EventListener
.
异步侦听器
如果您希望特定的测试执行事件监听器异步处理事件,
您可以使用 Spring 的定期@Async
支持.
有关更多详细信息,请参阅类级 javadoc@EventListener
.