使用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将从类路径根目录中的"/AppConfig.groovy"和"/TestConfig.groovy"加载
@ContextConfiguration({"/AppConfig.groovy", "/TestConfig.Groovy"}) (1)
class MyTest {
	// 类主体...
}
1 指定Groovy配置文件的位置。
@ExtendWith(SpringExtension::class)
// ApplicationContext将从类路径根目录中的"/AppConfig.groovy"和"/TestConfig.groovy"加载
@ContextConfiguration("/AppConfig.groovy", "/TestConfig.Groovy") (1)
class MyTest {
	// 类主体...
}
1 指定Groovy配置文件的位置。

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

  • Java

  • Kotlin

@ExtendWith(SpringExtension.class)
// ApplicationContext将从"classpath:com/example/MyTestContext.groovy"加载
@ContextConfiguration (1)
class MyTest {
	// 类主体...
}
1 从默认位置加载配置。
@ExtendWith(SpringExtension::class)
// ApplicationContext将从"classpath:com/example/MyTestContext.groovy"加载
@ContextConfiguration (1)
class MyTest {
	// 类主体...
}
1 从默认位置加载配置。
同时声明XML配置和Groovy脚本

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

以下清单显示了如何在集成测试中同时结合两者:

  • Java

  • Kotlin

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