|
对于最新的稳定版本,请使用 Spring Framework 7.0.6! |
使用Groovy脚本进行上下文配置
要通过使用Groovy脚本加载ApplicationContext进行测试,这些脚本基于
Groovy Bean定义DSL,您可以使用@ContextConfiguration注解
您的测试类,并通过locations或value属性
配置一个包含Groovy脚本资源位置的数组。Groovy脚本的
资源查找语义与XML配置文件中描述的规则相同。
|
启用Groovy脚本支持 支持使用Groovy脚本来加载一个ApplicationContext如果类路径中存在 Groovy,Spring TestContext 框架中的相关功能将自动启用。 |
以下示例演示如何指定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注解中同时省略locations和value属性,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脚本
您可以同时声明XML配置文件和Groovy脚本,方法是使用 以下清单展示了如何在集成测试中组合使用两者:
|