springboot测试使用ConfigurationProperties填充Map

Springboot test using ConfigurationProperties to fill Map

我有一个通用的 class 用于从我的应用程序 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

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

@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() 时,我得到了带有键值的映射,但在我的测试中,我仍然无法注入 bean KeyStoreConfig

@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() return 是一个 null 而不是带有键值的映射 我在我的配置中遗漏了什么吗?提前感谢您的帮助

因此,由于您在 @SpringBootTest 上使用 @ContextConfiguration 注释,因此某些 Spring 引导功能似乎被禁用,例如加载 application.propertiesapplication.yaml.

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

关于 spring 引导测试的一些有用链接:

Spring Boot Testing @ConfigurationProperties

@SpringBootTest vs @ContextConfiguration vs @Import in Spring Boot

我还发现 this article interesting, it's about difference between @ContextConfiguration and @SpringApplicationConfiguration,从 1.4 spring 引导版本开始不推荐使用 @SpringBootTest