【问题标题】:Fail to inject @Value in tests with Spring, Spock & Groovy无法在 Spring、Spock 和 Groovy 的测试中注入 @Value
【发布时间】: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)
    }
}

当我运行测试时,注入secretvalue 就是${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 {

它有效。属性被读取。但这不是我的目标,因为项目中有更多的属性,而且从手头到处定义它们会变得很麻烦。


你能发现我在这段代码中遗漏的问题吗?

【问题讨论】:

    标签: java spring groovy spock


    【解决方案1】:

    缺少的谜题是 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

    【讨论】:

      猜你喜欢
      • 2012-04-06
      • 1970-01-01
      • 2011-08-04
      • 1970-01-01
      • 2019-06-01
      • 2017-01-05
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多