測試執行事件

EventPublishingTestExecutionListener 提供了一種替代方法來實作自訂 TestExecutionListener。測試 ApplicationContext 中的元件可以監聽由 EventPublishingTestExecutionListener 發布的下列事件,每個事件都對應於 TestExecutionListener API 中的一個方法。

  • BeforeTestClassEvent

  • PrepareTestInstanceEvent

  • BeforeTestMethodEvent

  • BeforeTestExecutionEvent

  • AfterTestExecutionEvent

  • AfterTestMethodEvent

  • AfterTestClassEvent

這些事件可以用於各種原因,例如重設 Mock Bean 或追蹤測試執行。與實作自訂 TestExecutionListener 相比,取用測試執行事件的一個優勢是,測試執行事件可以由註冊在測試 ApplicationContext 中的任何 Spring Bean 取用,並且這些 Bean 可以直接受益於相依性注入和 ApplicationContext 的其他功能。 相反地,TestExecutionListener 不是 ApplicationContext 中的 Bean。

EventPublishingTestExecutionListener 預設為已註冊;但是,它僅在 ApplicationContext 已載入時發布事件。 這樣可以防止不必要或過早載入 ApplicationContext

因此,BeforeTestClassEvent 將在另一個 TestExecutionListener 載入 ApplicationContext 之後才會發布。 例如,使用預設註冊的 TestExecutionListener 實作集,BeforeTestClassEvent 將不會為第一個使用特定測試 ApplicationContext 的測試類別發布,但是 BeforeTestClassEvent 為同一測試套件中任何後續使用相同測試 ApplicationContext 的測試類別發布,因為當後續測試類別執行時,Context 將已載入(只要 Context 未透過 @DirtiesContext 或最大大小逐出策略從 ContextCache 中移除)。

如果您希望確保 BeforeTestClassEvent 始終為每個測試類別發布,則需要註冊一個在 beforeTestClass 回呼中載入 ApplicationContextTestExecutionListener,並且該 TestExecutionListener 必須在 EventPublishingTestExecutionListener 之前註冊。

同樣地,如果使用 @DirtiesContext 在給定測試類別中的最後一個測試方法之後從 Context 快取中移除 ApplicationContext,則不會為該測試類別發布 AfterTestClassEvent

為了監聽測試執行事件,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。