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