【发布时间】:2020-12-22 10:31:31
【问题描述】:
在使用 Spring Boot 和 Groovy 在 Spock 中进行测试期间,我在将 @Value('${mybean.secret}') 属性注入到我的 bean 时遇到问题。
我有一个非常简单的测试类MyBeanTest
@ContextConfiguration(classes = [
MyAppConfig
])
@PropertySource([
"classpath:context/default-properties.yml"
])
class MyBeanTest extends Specification {
@Autowired
MyBean myBean
def "should populate properties "() {
expect:
myBean.secretProperty == "iCantTellYou"
}
}
和MyAppConfig.groovy 一样:
@Configuration
class MyAppConfig {
@Bean
MyBean credential(@Value('${mybean.secret}') String secret) {
return new MyBean(secret)
}
}
当我运行测试时,注入secret 的value 就是${mybean.secret}。
真正的价值不是从properties文件中注入的我附在测试规范中。
由于 Groovy,我在 @Value 上使用单引号。带有$ 符号的双quote 使其被groovy GString 机制处理。
但是,在常规应用程序运行时不会出现此问题。
如果我启动应用程序并将断点放在MyAppConfig#credential 方法上,则可以从属性文件中正确读取secret 值,其配置如下:
@Configuration
@PropertySource(["classpath:context/default-properties.yml"])
class PropertiesConfig {
}
当我这样指定属性时:
@TestPropertySource(properties = [
"mybean.secret=xyz"
])
class MyBeanTest extends Specification {
它有效。属性被读取。但这不是我的目标,因为项目中有更多的属性,而且从手头到处定义它们会变得很麻烦。
你能发现我在这段代码中遗漏的问题吗?
【问题讨论】: