使用 XML 資源進行上下文配置

要使用 XML 配置檔案為測試載入 ApplicationContext,請使用 @ContextConfiguration 註解測試類,並將 locations 屬性配置為一個包含 XML 配置元資料資源位置的陣列。普通或相對路徑(例如 context.xml)被視為相對於定義測試類的包的類路徑資源。以斜槓開頭的路徑被視為絕對類路徑位置(例如 /org/example/config.xml)。表示資源 URL 的路徑(即帶有 classpath:file:http: 等字首的路徑)將按原樣使用。

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from "/app-config.xml" and
// "/test-config.xml" in the root of the classpath
@ContextConfiguration(locations = {"/app-config.xml", "/test-config.xml"}) (1)
class MyTest {
	// class body...
}
1 將 locations 屬性設定為 XML 檔案列表。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from "/app-config.xml" and
// "/test-config.xml" in the root of the classpath
@ContextConfiguration(locations = ["/app-config.xml", "/test-config.xml"]) (1)
class MyTest {
	// class body...
}
1 將 locations 屬性設定為 XML 檔案列表。

@ContextConfiguration 透過標準的 Java value 屬性支援 locations 屬性的別名。因此,如果您不需要在 @ContextConfiguration 中宣告額外的屬性,則可以省略 locations 屬性名稱的宣告,並使用以下示例中展示的簡寫格式宣告資源位置

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
@ContextConfiguration({"/app-config.xml", "/test-config.xml"}) (1)
class MyTest {
	// class body...
}
1 不使用 locations 屬性指定 XML 檔案。
@ExtendWith(SpringExtension::class)
@ContextConfiguration("/app-config.xml", "/test-config.xml") (1)
class MyTest {
	// class body...
}
1 不使用 locations 屬性指定 XML 檔案。

如果您從 @ContextConfiguration 註解中省略 locationsvalue 屬性,TestContext 框架會嘗試檢測預設的 XML 資源位置。具體來說,GenericXmlContextLoaderGenericXmlWebContextLoader 會根據測試類的名稱檢測預設位置。如果您的類名為 com.example.MyTest,則 GenericXmlContextLoader 會從 "classpath:com/example/MyTest-context.xml" 載入應用程式上下文。以下示例展示瞭如何實現這一點

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 從預設位置載入配置。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTest-context.xml"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 從預設位置載入配置。