使用 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 不使用 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.MyTestGenericXmlContextLoader 會從 "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 從預設位置載入配置。
© . This site is unofficial and not affiliated with VMware.