關鍵抽象概念
框架的核心由 TestContextManager
類別以及 TestContext
、TestExecutionListener
和 SmartContextLoader
介面組成。每個測試類別都會建立一個 TestContextManager
(例如,在 JUnit Jupiter 中執行單一測試類別中的所有測試方法)。 TestContextManager
反過來管理一個 TestContext
,其中包含目前測試的 Context。 TestContextManager
也會在測試進度中更新 TestContext
的狀態,並委派給 TestExecutionListener
實作,這些實作透過提供相依性注入、管理交易等等來檢測實際的測試執行。 SmartContextLoader
負責為給定的測試類別載入 ApplicationContext
。 如需各種實作的更多資訊和範例,請參閱 javadoc 和 Spring 測試套件。
TestContext
TestContext
封裝了執行測試的 Context(與使用的實際測試框架無關),並為其負責的測試實例提供 Context 管理和快取支援。 TestContext
也會委派給 SmartContextLoader
,以在需要時載入 ApplicationContext
。
TestContextManager
TestContextManager
是 Spring TestContext 框架的主要進入點,負責管理單一 TestContext
,並在明確定義的測試執行點向每個已註冊的 TestExecutionListener
發出事件訊號
-
在特定測試框架的任何「before class」或「before all」方法之前。
-
測試實例後處理。
-
在特定測試框架的任何「before」或「before each」方法之前。
-
緊接在測試方法執行之前,但在測試設定之後。
-
緊接在測試方法執行之後,但在測試拆解之前。
-
在特定測試框架的任何「after」或「after each」方法之後。
-
在特定測試框架的任何「after class」或「after all」方法之後。
TestExecutionListener
TestExecutionListener
定義了 API,用於回應已註冊接聽器的 TestContextManager
發佈的測試執行事件。 請參閱 TestExecutionListener
組態。
Context 載入器
ContextLoader
是用於為 Spring TestContext 框架管理的整合測試載入 ApplicationContext
的策略介面。 您應該實作 SmartContextLoader
而不是此介面,以提供對組件類別、作用中 Bean 定義 Profile、測試屬性來源、Context 階層和 WebApplicationContext
支援的支援。
SmartContextLoader
是 ContextLoader
介面的延伸,取代了原始最簡化的 ContextLoader
SPI。 具體而言,SmartContextLoader
可以選擇處理資源位置、組件類別或 Context Initializer。 此外,SmartContextLoader
可以在其載入的 Context 中設定作用中 Bean 定義 Profile 和測試屬性來源。
Spring 提供下列實作
-
DelegatingSmartContextLoader
:兩個預設載入器之一,它在內部委派給AnnotationConfigContextLoader
、GenericXmlContextLoader
或GenericGroovyXmlContextLoader
,具體取決於為測試類別宣告的組態,或預設位置或預設組態類別的存在。 只有在類別路徑上存在 Groovy 時,才會啟用 Groovy 支援。 -
WebDelegatingSmartContextLoader
:兩個預設載入器之一,它在內部委派給AnnotationConfigWebContextLoader
、GenericXmlWebContextLoader
或GenericGroovyXmlWebContextLoader
,具體取決於為測試類別宣告的組態,或預設位置或預設組態類別的存在。 只有在測試類別上存在@WebAppConfiguration
時,才會使用 WebContextLoader
。 只有在類別路徑上存在 Groovy 時,才會啟用 Groovy 支援。 -
AnnotationConfigContextLoader
:從組件類別載入標準ApplicationContext
。 -
AnnotationConfigWebContextLoader
:從組件類別載入WebApplicationContext
。 -
GenericGroovyXmlContextLoader
:從作為 Groovy 腳本或 XML 組態檔的資源位置載入標準ApplicationContext
。 -
GenericGroovyXmlWebContextLoader
:從作為 Groovy 腳本或 XML 組態檔的資源位置載入WebApplicationContext
。 -
GenericXmlContextLoader
:從 XML 資源位置載入標準ApplicationContext
。 -
GenericXmlWebContextLoader
:從 XML 資源位置載入WebApplicationContext
。