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

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

啟用 Groovy 指令碼支援
如果 Groovy 位於類路徑中,則 Spring TestContext 框架中用於載入 ApplicationContext 的 Groovy 指令碼支援會自動啟用。

以下示例展示瞭如何指定 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 框架會嘗試檢測預設的 Groovy 指令碼。具體來說,GenericGroovyXmlContextLoaderGenericGroovyXmlWebContextLoader 會根據測試類的名稱檢測預設位置。如果您的類名為 com.example.MyTest,Groovy 上下文載入器會從 "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...
}
© . This site is unofficial and not affiliated with VMware.