[英]Fail to inject @Value in tests with Spring, Spock & Groovy
在使用 Spring Boot 和 Groovy 在 Spock 中进行测试期间,我在将@Value('${mybean.secret}')
属性注入我的 bean 时遇到问题。
我有一个非常简单的测试 class 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 {
有用。 属性被读取。 但这不是我的目标,因为项目中有更多的属性,而且从手头到处定义它们会变得很麻烦。
你能发现我在这段代码中遗漏的问题吗?
缺少的难题是 YamlPropertySourceFactory。
public class YamlPropertySourceFactory implements PropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource)
throws IOException {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(encodedResource.getResource());
Properties properties = factory.getObject();
return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
}
我正在使用具有嵌套属性的yml
属性文件:
mybean:
secret: xyz
并且 Spring 没有正确加载它们。
我必须更新@PropertySource
注释以及以下内容:
@Configuration
@PropertySource(
value = ["classpath:context/default-properties.yml"],
factory = YamlPropertySourceFactory.class
)
class PropertiesConfig {
}
现在它就像一个魅力。
我在 Baeldung 网站上了解到这一点 => https://www.baeldung.com/spring-yaml-propertysource
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.