此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Framework 6.2.0! |
使用 Groovy 脚本进行上下文配置
要加载ApplicationContext
对于您的测试,您可以使用使用 Groovy Bean 定义 DSL 的 Groovy 脚本进行注释
你的 test 类与@ContextConfiguration
并配置locations
或value
属性替换为包含 Groovy 脚本资源位置的数组。资源
Groovy 脚本的查找语义与 XML 配置文件中描述的相同。
启用 Groovy 脚本支持 支持使用 Groovy 脚本加载ApplicationContext 在Spring
如果 Groovy 在 Classpath 上,则会自动启用 TestContext Framework。 |
下面的示例展示了如何指定 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 脚本
您可以使用
这 下面的清单显示了如何在集成测试中将两者结合起来:
|