載入 WebApplicationContext

若要指示 TestContext 框架載入 WebApplicationContext 而非標準 ApplicationContext,您可以使用 @WebAppConfiguration 註解對應的測試類別。

測試類別上存在 @WebAppConfiguration 會指示 TestContext 框架 (TCF) 應為您的整合測試載入 WebApplicationContext (WAC)。在背景中,TCF 確保建立 MockServletContext 並提供給您的測試 WAC。預設情況下,您的 MockServletContext 的基本資源路徑設定為 src/main/webapp。這被解釋為相對於 JVM 根目錄的路徑 (通常是專案的路徑)。如果您熟悉 Maven 專案中網路應用程式的目錄結構,您就會知道 src/main/webapp 是 WAR 根目錄的預設位置。如果您需要覆寫此預設值,您可以為 @WebAppConfiguration 註解提供替代路徑 (例如,@WebAppConfiguration("src/test/webapp"))。如果您希望從類別路徑而非檔案系統參考基本資源路徑,則可以使用 Spring 的 classpath: 前綴。

請注意,Spring 對於 WebApplicationContext 實作的測試支援與其對標準 ApplicationContext 實作的支援相當。使用 WebApplicationContext 進行測試時,您可以自由地使用 @ContextConfiguration 宣告 XML 配置檔案、Groovy 腳本或 @Configuration 類別。您也可以自由地使用任何其他測試註解,例如 @ActiveProfiles@TestExecutionListeners@Sql@Rollback 等。

本節其餘範例顯示了載入 WebApplicationContext 的各種配置選項。以下範例顯示 TestContext 框架對慣例優於配置的支援

慣例
  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)

// defaults to "file:src/main/webapp"
@WebAppConfiguration

// detects "WacTests-context.xml" in the same package
// or static nested @Configuration classes
@ContextConfiguration
class WacTests {
	//...
}
@ExtendWith(SpringExtension::class)

// defaults to "file:src/main/webapp"
@WebAppConfiguration

// detects "WacTests-context.xml" in the same package
// or static nested @Configuration classes
@ContextConfiguration
class WacTests {
	//...
}

如果您使用 @WebAppConfiguration 註解測試類別,而不指定資源基本路徑,則資源路徑實際上預設為 file:src/main/webapp。同樣地,如果您宣告 @ContextConfiguration 而不指定資源 locations、元件 classes 或 context initializers,Spring 會嘗試透過使用慣例來偵測配置的存在 (也就是說,與 WacTests 類別或靜態巢狀 @Configuration 類別位於相同套件中的 WacTests-context.xml)。

以下範例顯示如何使用 @WebAppConfiguration 明確宣告資源基本路徑,以及使用 @ContextConfiguration 宣告 XML 資源位置

預設資源語意
  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)

// file system resource
@WebAppConfiguration("webapp")

// classpath resource
@ContextConfiguration("/spring/test-servlet-config.xml")
class WacTests {
	//...
}
@ExtendWith(SpringExtension::class)

// file system resource
@WebAppConfiguration("webapp")

// classpath resource
@ContextConfiguration("/spring/test-servlet-config.xml")
class WacTests {
	//...
}

這裡需要注意的重要事項是這兩個註解的路徑具有不同的語意。預設情況下,@WebAppConfiguration 資源路徑是基於檔案系統的,而 @ContextConfiguration 資源位置是基於類別路徑的。

以下範例顯示,我們可以透過指定 Spring 資源前綴來覆寫這兩個註解的預設資源語意

明確資源語意
  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)

// classpath resource
@WebAppConfiguration("classpath:test-web-resources")

// file system resource
@ContextConfiguration("file:src/main/webapp/WEB-INF/servlet-config.xml")
class WacTests {
	//...
}
@ExtendWith(SpringExtension::class)

// classpath resource
@WebAppConfiguration("classpath:test-web-resources")

// file system resource
@ContextConfiguration("file:src/main/webapp/WEB-INF/servlet-config.xml")
class WacTests {
	//...
}

將此範例中的註解與前一個範例進行比較。