測試執行事件
EventPublishingTestExecutionListener
提供了一種實現自定義 TestExecutionListener
的替代方法。測試的 ApplicationContext
中的元件可以監聽由 EventPublishingTestExecutionListener
釋出的以下事件,每個事件都對應於 TestExecutionListener
API 中的一個方法。
-
BeforeTestClassEvent
-
PrepareTestInstanceEvent
-
BeforeTestMethodEvent
-
BeforeTestExecutionEvent
-
AfterTestExecutionEvent
-
AfterTestMethodEvent
-
AfterTestClassEvent
這些事件可以出於各種原因被消費,例如重置 mock 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。