測試執行事件
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
介面。 或者,Listener 方法可以使用 @EventListener
進行註解,並組態為監聽上面列出的特定事件類型之一(請參閱 基於註解的事件 Listener)。 由於此方法的普及,Spring 提供了以下專用的 @EventListener
註解,以簡化測試執行事件 Listener 的註冊。 這些註解位於 org.springframework.test.context.event.annotation
套件中。
-
@BeforeTestClass
-
@PrepareTestInstance
-
@BeforeTestMethod
-
@BeforeTestExecution
-
@AfterTestExecution
-
@AfterTestMethod
-
@AfterTestClass
例外處理
預設情況下,如果測試執行事件 Listener 在取用事件時擲回例外,則該例外將傳播到使用中的底層測試框架(例如 JUnit 或 TestNG)。 例如,如果取用 BeforeTestMethodEvent
導致例外,則對應的測試方法將因例外而失敗。 相反地,如果非同步測試執行事件 Listener 擲回例外,則該例外將不會傳播到底層測試框架。 有關非同步例外處理的更多詳細資訊,請查閱 @EventListener
的類別層級 Javadoc。
非同步 Listener
如果您希望特定測試執行事件 Listener 非同步處理事件,則可以使用 Spring 的 常規 @Async
支援。 有關更多詳細資訊,請查閱 @EventListener
的類別層級 Javadoc。