關鍵抽象

該框架的核心包括 TestContextManager 類以及 TestContextTestExecutionListenerSmartContextLoader 介面。每個測試類都會建立一個 TestContextManager(例如,用於執行 JUnit Jupiter 中單個測試類內的所有測試方法)。TestContextManager 反過來管理一個 TestContext,該 TestContext 儲存當前測試的上下文。TestContextManager 還隨著測試的進行更新 TestContext 的狀態,並將任務委託給 TestExecutionListener 實現,這些實現透過提供依賴注入、管理事務等來檢測實際的測試執行。SmartContextLoader 負責為給定的測試類載入一個 ApplicationContext。有關各種實現的更多資訊和示例,請參閱 javadoc 和 Spring 測試套件。

TestContext

TestContext 封裝了測試執行的上下文(與使用的實際測試框架無關),併為其負責的測試例項提供上下文管理和快取支援。如果需要,TestContext 還會委託給 SmartContextLoader 來載入 ApplicationContext

TestContextManager

TestContextManager 是 Spring TestContext Framework 的主要入口點,負責管理單個 TestContext 並在定義明確的測試執行點向每個已註冊的 TestExecutionListener 傳送事件。

  • 在特定測試框架的任何“before class”或“before all”方法之前。

  • 測試例項後處理。

  • 在特定測試框架的任何“before”或“before each”方法之前。

  • 緊接在測試方法執行之前,但在測試設定之後。

  • 緊接在測試方法執行之後,但在測試拆卸之前。

  • 在特定測試框架的任何“after”或“after each”方法之後。

  • 在特定測試框架的任何“after class”或“after all”方法之後。

TestExecutionListener

TestExecutionListener 定義了對與其註冊的 TestContextManager 釋出的測試執行事件做出反應的 API。請參閱 TestExecutionListener 配置

Context 載入器

ContextLoader 是一個策略介面,用於為 Spring TestContext Framework 管理的整合測試載入 ApplicationContext。你應該實現 SmartContextLoader 而不是此介面,以提供對元件類、活動 bean 定義 profile、測試屬性源、上下文層次結構和 WebApplicationContext 支援。

SmartContextLoaderContextLoader 介面的擴充套件,取代了最初的最小 ContextLoader SPI。具體來說,SmartContextLoader 可以選擇處理資源位置、元件類或上下文初始化器。此外,SmartContextLoader 可以在其載入的上下文中設定活動 bean 定義 profile 和測試屬性源。

Spring 提供以下實現

  • DelegatingSmartContextLoader:兩個預設載入器之一,它根據測試類宣告的配置或預設位置或預設配置類的存在,內部委託給 AnnotationConfigContextLoaderGenericXmlContextLoaderGenericGroovyXmlContextLoader。僅當 Groovy 在類路徑上時才啟用 Groovy 支援。

  • WebDelegatingSmartContextLoader:兩個預設載入器之一,它根據測試類宣告的配置或預設位置或預設配置類的存在,內部委託給 AnnotationConfigWebContextLoaderGenericXmlWebContextLoaderGenericGroovyXmlWebContextLoader。僅當測試類上存在 @WebAppConfiguration 時才使用 web ContextLoader。僅當 Groovy 在類路徑上時才啟用 Groovy 支援。

  • AnnotationConfigContextLoader:從元件類載入標準 ApplicationContext

  • AnnotationConfigWebContextLoader:從元件類載入 WebApplicationContext

  • GenericGroovyXmlContextLoader:從作為 Groovy 指令碼或 XML 配置檔案的資源位置載入標準 ApplicationContext

  • GenericGroovyXmlWebContextLoader:從作為 Groovy 指令碼或 XML 配置檔案的資源位置載入 WebApplicationContext

  • GenericXmlContextLoader:從 XML 資源位置載入標準 ApplicationContext

  • GenericXmlWebContextLoader:從 XML 資源位置載入 WebApplicationContext