使用 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...
}