使用 Groovy 指令碼進行上下文配置

要使用採用 Groovy Bean Definition DSL 的 Groovy 指令碼為測試載入 ApplicationContext,您可以使用 @ContextConfiguration 註解您的測試類,並配置包含 Groovy 指令碼資源位置的陣列的 locationsvalue 屬性。Groovy 指令碼的資源查詢語義與 XML 配置檔案中描述的相同。

啟用 Groovy 指令碼支援
如果 Groovy 在類路徑上,則 Spring TestContext Framework 中使用 Groovy 指令碼載入 ApplicationContext 的支援會自動啟用。

以下示例展示如何指定 Groovy 配置檔案

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from "/AppConfig.groovy" and
// "/TestConfig.groovy" in the root of the classpath
@ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"}) (1)
class MyTest {
	// class body...
}
1 指定 Groovy 配置檔案的位置。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from "/AppConfig.groovy" and
// "/TestConfig.groovy" in the root of the classpath
@ContextConfiguration("/AppConfig.groovy", "/TestConfig.Groovy") (1)
class MyTest {
	// class body...
}
1 指定 Groovy 配置檔案的位置。

如果您省略 @ContextConfiguration 註解的 locationsvalue 屬性,TestContext framework 將嘗試檢測預設的 Groovy 指令碼。具體來說,GenericGroovyXmlContextLoaderGenericGroovyXmlWebContextLoader 會根據測試類的名稱檢測預設位置。如果您的類名為 com.example.MyTest,則 Groovy context loader 將從 "classpath:com/example/MyTestContext.groovy" 載入您的應用程式上下文。以下示例展示如何使用預設設定

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTestContext.groovy"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 從預設位置載入配置。
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTestContext.groovy"
@ContextConfiguration (1)
class MyTest {
	// class body...
}
1 從預設位置載入配置。
同時宣告 XML 配置和 Groovy 指令碼

您可以使用 @ContextConfigurationlocationsvalue 屬性同時宣告 XML 配置檔案和 Groovy 指令碼。如果配置的資源位置路徑以 .xml 結尾,則使用 XmlBeanDefinitionReader 載入。否則,使用 GroovyBeanDefinitionReader 載入。

以下列表展示瞭如何在整合測試中結合使用它們

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "/app-config.xml" and "/TestConfig.groovy"
@ContextConfiguration({ "/app-config.xml", "/TestConfig.groovy" })
class MyTest {
	// class body...
}
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "/app-config.xml" and "/TestConfig.groovy"
@ContextConfiguration("/app-config.xml", "/TestConfig.groovy")
class MyTest {
	// class body...
}