跳到主要内容
版本:7.0.3

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

Hunyuan 7b 中英对照 Context Configuration with Groovy Scripts

要使用Groovy脚本为测试加载ApplicationContext(这些脚本采用了Groovy Bean Definition DSL),你可以在测试类上添加@ContextConfiguration注解,并通过一个数组来配置locationsvalue属性,该数组包含Groovy脚本的资源路径。Groovy脚本的资源查找规则与XML配置文件中描述的规则相同。

提示

启用Groovy脚本支持

如果在类路径(classpath)中包含了Groovy,那么在Spring TestContext框架中就可以自动使用Groovy脚本来加载ApplicationContext了。

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

@ExtendWith(SpringExtension.class)
// ApplicationContext将从类路径根目录下的"/AppConfig.groovy"和"/TestConfig.groovy"文件中加载
@ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"}) 1
class MyTest {
// 类体...
}
  • 指定Groovy配置文件的位置。

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

@ExtendWith(SpringExtension.class)
// ApplicationContext将从以下位置加载:
// "classpath:com/example/MyTestContext.groovy"
@ContextConfiguration 1
class MyTest {
// 类体...
}
  • 从默认位置加载配置。

提示

同时声明XML配置和Groovy脚本

您可以使用@ContextConfigurationlocationsvalue属性来同时声明XML配置文件和Groovy脚本。如果配置资源的路径以.xml结尾,则会使用XmlBeanDefinitionReader进行加载;否则,将使用GroovyBeanDefinitionReader进行加载。

以下示例展示了如何在集成测试中同时使用这两种方式:

@ExtendWith(SpringExtension.class)
// ApplicationContext将从
// "/app-config.xml" 和 "/TestConfig.groovy" 中加载
@ContextConfiguration({ "/app-config.xml", "/TestConfig.groovy" })
class MyTest {
// 类体...
}