使用 XML 資源進行內容組態

若要使用 XML 組態檔為您的測試載入 ApplicationContext,請使用 @ContextConfiguration 註解您的測試類別,並使用包含 XML 組態中繼資料資源位置的陣列來配置 locations 屬性。純粹或相對路徑 (例如,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 指定 XML 檔案而不使用 locations 屬性。
@ExtendWith(SpringExtension::class)
@ContextConfiguration("/app-config.xml", "/test-config.xml") (1)
class MyTest {
	// class body...
}
1 指定 XML 檔案而不使用 locations 屬性。

如果您從 @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 從預設位置載入組態。