載入 WebApplicationContext
要指示 TestContext 框架載入 WebApplicationContext
而不是標準的 ApplicationContext
,你可以使用 @WebAppConfiguration
註解相應的測試類。
在你的測試類上存在 @WebAppConfiguration
註解指示 TestContext 框架 (TCF) 為你的整合測試載入 WebApplicationContext
(WAC)。在後臺,TCF 會確保建立一個 MockServletContext
並將其提供給你的測試 WAC。預設情況下,你的 MockServletContext
的基本資源路徑被設定為 src/main/webapp
。這被解釋為相對於 JVM 根目錄(通常是你的專案路徑)的路徑。如果你熟悉 Maven 專案中 Web 應用程式的目錄結構,你會知道 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
或上下文 initializers
,Spring 會嘗試使用約定來檢測你的配置是否存在(即,與 WacTests
類在同一包中的 WacTests-context.xml
或靜態巢狀的 @Configuration
類)。
以下示例展示瞭如何使用 @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 {
//...
}
對比此示例與前一個示例中的註釋。