此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
测试执行事件
这EventPublishingTestExecutionListener
在 Spring Framework 5.2 中引入的
实现自定义的替代方法TestExecutionListener
.组件
test 的ApplicationContext
可以监听EventPublishingTestExecutionListener
,每个 API 都对应于TestExecutionListener
应用程序接口。
-
BeforeTestClassEvent
-
PrepareTestInstanceEvent
-
BeforeTestMethodEvent
-
BeforeTestExecutionEvent
-
AfterTestExecutionEvent
-
AfterTestMethodEvent
-
AfterTestClassEvent
这些事件可能由于各种原因而被使用,例如重置 mock bean 或跟踪
测试执行。使用测试执行事件而不是实现
自定义TestExecutionListener
是测试执行事件可以被任何
在测试中注册的 Spring beanApplicationContext
,这样的 bean 可能会受益
直接从依赖项注入和ApplicationContext
.在
contrast 中,一个TestExecutionListener
不是ApplicationContext
.
这 因此,一个 如果您希望确保 同样,如果 |
为了监听测试执行事件,Spring bean 可以选择实现org.springframework.context.ApplicationListener
接口。或者,侦听器
方法可以使用@EventListener
并配置为侦听
上面列出的特定事件类型(请参阅基于 Comments 的事件侦听器)。
由于这种方法的流行, Spring 提供了以下专用的@EventListener
注解来简化测试执行事件侦听器的注册。
这些注释位于org.springframework.test.context.event.annotation
包。
-
@BeforeTestClass
-
@PrepareTestInstance
-
@BeforeTestMethod
-
@BeforeTestExecution
-
@AfterTestExecution
-
@AfterTestMethod
-
@AfterTestClass
异常处理
默认情况下,如果测试执行事件侦听器在使用
事件,该异常将传播到正在使用的底层测试框架(例如
JUnit 或 TestNG)。例如,如果BeforeTestMethodEvent
结果
异常,则相应的测试方法将因异常而失败。在
相反,如果异步测试执行事件侦听器引发异常,则
exception 不会传播到底层测试框架。有关更多详细信息
异步异常处理,请参阅类级 javadoc 以获取@EventListener
.
异步侦听器
如果您希望特定的测试执行事件侦听器异步处理事件,
您可以使用 Spring 的定期@Async
支持.有关更多详细信息,请参阅类级 javadoc 以获取@EventListener
.