首页 > 解决方案 > Springboot测试使用ConfigurationProperties填充Map

问题描述

我有一个通用类,用于从我的应用程序 yaml 文件中加载一些键,这是我的 yaml 文件:

errabi.security:
  keyStores:
      jwt:
        type: JKS
        location: classpath:keystore.jks
        keyStorePassword: password # to be encrypted
        keyPassword: password # to be encrypted
        keyAlias: errabi
      jwe:
        type: JKS
        location: classpath:keystore.jks
        keyStorePassword: password # to be encrypted
        keyPassword: password # to be encrypted
        keyAlias: errabi

这是我用来根据一些键加载值的类:

@Configuration
@ConfigurationProperties(prefix = "errabi.security")
public class KeyStoreConfig {

    private Map<String, KeyStoreConfig.KeyStoreConfiguration> keyStores;

    public Map<String, KeyStoreConfiguration> getKeyStores() {
        return keyStores;
    }

    public void setKeyStores(Map<String, KeyStoreConfiguration> keyStores) {
        this.keyStores = keyStores;
    }

    public static class KeyStoreConfiguration {
          private String type;
          private String location;
          private char [] keyStorePassword;
          private char [] keyPassword;
          private String keyAlias;
          // getters and setters
}
}

在我的应用程序中,当我调用 KeyStoreConfig.getKeyStores() 方法时,我得到了带有键值的映射,但在我的测试中,我仍然无法注入 beanKeyStoreConfig

@SpringBootTest
@ContextConfiguration(classes = KeyStoreConfig.class)
class JWEUtilTest extends Specification {
    @Autowired
    private KeyStoreConfig keyStoreConfig;
    
    // in the debug mode the KeyStoreConfig.getKeyStores() return a null instead of a map with keyvalues
}

在我的测试过程中,NullPointerException当我调试时,我看到KeyStoreConfig.getKeyStores()返回 null 而不是带有键值的映射,我是否错过了配置中的某些内容?提前感谢您的帮助

标签: javaspring-bootjunitspring-test

解决方案


因此,由于您@ContextConfiguration在.@SpringBootTestapplication.propertiesapplication.yaml

要手动启用它,您应该添加到您的测试类:@EnableConfigurationProperties(KeyStoreConfig.class).

有关 Spring Boot 测试的一些有用链接:

Spring Boot 测试@ConfigurationProperties

@SpringBootTest 与 @ContextConfiguration 与 Spring Boot 中的 @Import

我还发现这篇@ContextConfiguration文章很有趣,它是关于和之间的区别@SpringApplicationConfiguration,从 1.4 春季启动版本开始不推荐使用@SpringBootTest.


推荐阅读