使用 Groovy 脚本配置上下文
要通过使用 Groovy Bean Definition DSL 的 Groovy 脚本来为你的测试加载 ApplicationContext
,你可以使用 @ContextConfiguration
注解你的测试类,并通过 locations
或 value
属性配置一个包含 Groovy 脚本资源位置的数组。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 {
// class body...
}
指定 Groovy 配置文件的位置。
@ExtendWith(SpringExtension::class)
// ApplicationContext 将从类路径根目录下的 "/AppConfig.groovy" 和
// "/TestConfig.groovy" 加载
@ContextConfiguration("/AppConfig.groovy", "/TestConfig.Groovy") 1
class MyTest {
// class body...
}
指定 Groovy 配置文件的位置。
如果从 @ContextConfiguration
注解中省略了 locations
和 value
属性,TestContext 框架会尝试检测一个默认的 Groovy 脚本。具体来说,GenericGroovyXmlContextLoader
和 GenericGroovyXmlWebContextLoader
会根据测试类的名称检测默认的位置。如果你的类名为 com.example.MyTest
,Groovy 上下文加载器会从 "classpath:com/example/MyTestContext.groovy"
加载你的应用上下文。以下示例展示了如何使用默认值:
- Java
- Kotlin
@ExtendWith(SpringExtension.class)
// ApplicationContext 将从
// "classpath:com/example/MyTestContext.groovy" 加载
@ContextConfiguration 1
class MyTest {
// class body...
}
从默认位置加载配置。
@ExtendWith(SpringExtension::class)
// ApplicationContext 将从
// "classpath:com/example/MyTestContext.groovy" 加载
@ContextConfiguration 1
class MyTest {
// class body...
}
从默认位置加载配置。
同时声明 XML 配置和 Groovy 脚本
你可以通过使用 @ContextConfiguration
的 locations
或 value
属性来同时声明 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 {
// 类体...
}