|
对于最新稳定版本,请使用 Spring Framework 7.0.6! |
使用 Groovy 脚本进行上下文配置
要使用采用Groovy Bean 定义 DSL的 Groovy 脚本为您的测试加载../../../core/beans/basics.html#groovy-bean-definition-dsl,您可以使用@ContextConfiguration注解标注您的测试类,并将locations或value属性配置为包含 Groovy 脚本资源位置的数组。Groovy 脚本的资源查找语义与XML 配置文件中描述的语义相同。
启用 Groovy 脚本支持
如果类路径中存在 Groovy,则 Spring TestContext 框架会自动启用使用 Groovy 脚本加载 ApplicationContext 的支持。 |
以下示例展示了如何指定 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 配置文件的位置。 |
如果从 locations 注解中同时省略 value 和 @ContextConfiguration 属性,TestContext 框架会尝试检测一个默认的 Groovy 脚本。
具体来说,GenericGroovyXmlContextLoader 和 GenericGroovyXmlWebContextLoader
会根据测试类的名称来检测默认位置。如果你的类名为
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 脚本
你可以通过使用 以下示例展示了如何在集成测试中同时结合使用这两者:
|