使用 Groovy 脚本进行上下文配置

要使用 Groovy Bean 定义 DSL 的 Groovy 脚本为测试加载 ApplicationContext,你可以使用 @ContextConfiguration 注解你的测试类,并配置 locationsvalue 属性,使其包含 Groovy 脚本资源位置的数组。Groovy 脚本的资源查找语义与 XML 配置文件 中描述的相同。

启用 Groovy 脚本支持

如果 Groovy 在类路径上,Spring TestContext 框架中对使用 Groovy 脚本加载 ApplicationContext 的支持会自动启用。

以下示例展示了如何指定 Groovy 配置文件:

Java
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from "/AppConfig.groovy" and
// "/TestConfig.groovy" in the root of the classpath
@ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"}) [id="CO1-1"]1
class MyTest {
	// class body...
}
<1>  指定 Groovy 配置文件的位置。
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") [id="CO2-1"][id="CO1-1"][id="CO2-1"](1)
class MyTest {
	// class body...
}
<1>  指定 Groovy 配置文件的位置。

如果你省略 @ContextConfiguration 注解中的 locationsvalue 属性,TestContext 框架会尝试检测默认的 Groovy 脚本。具体来说,GenericGroovyXmlContextLoaderGenericGroovyXmlWebContextLoader 会根据测试类的名称检测默认位置。如果你的类名为 com.example.MyTest,Groovy 上下文加载器会从 "classpath:com/example/MyTestContext.groovy" 加载你的应用程序上下文。以下示例展示了如何使用默认值:

Java
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTestContext.groovy"
@ContextConfiguration [id="CO3-1"][id="CO1-2"][id="CO3-1"](1)
class MyTest {
	// class body...
}
<1>  从默认位置加载配置。
Kotlin
@ExtendWith(SpringExtension::class)
// ApplicationContext will be loaded from
// "classpath:com/example/MyTestContext.groovy"
@ContextConfiguration [id="CO4-1"][id="CO1-3"][id="CO4-1"](1)
class MyTest {
	// class body...
}
<1>  从默认位置加载配置。
同时声明 XML 配置和 Groovy 脚本

你可以通过使用 @ContextConfigurationlocationsvalue 属性同时声明 XML 配置文件和 Groovy 脚本。如果配置的资源位置路径以 .xml 结尾,它将使用 XmlBeanDefinitionReader 加载。否则,它将使用 GroovyBeanDefinitionReader 加载。 以下列表展示了如何在集成测试中将两者结合:

Java
@ExtendWith(SpringExtension.class)
// ApplicationContext will be loaded from
// "/app-config.xml" and "/TestConfig.groovy"
@ContextConfiguration({ "/app-config.xml", "/TestConfig.groovy" })
class MyTest {
	// class body...
}
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...
}