|
对于最新的稳定版本,请使用 Spring Framework 6.2.10! |
测试执行事件
这EventPublishingTestExecutionListenerSpring Framework 5.2 中引入的提供了一个实现自定义TestExecutionListener. 组件中的test 的ApplicationContext可以监听EventPublishingTestExecutionListener,每个方法对应于TestExecutionListener应用程序接口。
-
BeforeTestClassEvent -
PrepareTestInstanceEvent -
BeforeTestMethodEvent -
BeforeTestExecutionEvent -
AfterTestExecutionEvent -
AfterTestMethodEvent -
AfterTestClassEvent
这些事件可能会因各种原因而被使用,例如重置模拟 Bean 或跟踪测试执行。使用测试执行事件而不是实现自定义TestExecutionListener测试执行事件可以被任何Spring bean 在测试中注册ApplicationContext,并且此类 bean 可能会受益直接来自依赖注入和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.