測試執行事件
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。