【问题标题】:Springboot test using ConfigurationProperties to fill MapSpring Boot 测试使用 Configuration Properties 填充 Map
【发布时间】:2021-11-17 22:30:07
【问题描述】:

我有一个通用类,用于从我的应用程序 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() 方法时,我得到了带有键值的映射,但在我的测试中,我仍然无法注入 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() 返回一个空值而不是一个带有键值的映射 我错过了我的配置吗?在此先感谢您的帮助

【问题讨论】:

    标签: java spring-boot junit spring-test


    【解决方案1】:

    因此,由于您在@SpringBootTest 上使用@ContextConfiguration 注释,因此似乎禁用了某些Spring Boot 功能,例如加载application.propertiesapplication.yaml 中指定的外部属性。

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

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

    Spring Boot Testing @ConfigurationProperties

    @SpringBootTest vs @ContextConfiguration vs @Import in Spring Boot

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

    【讨论】:

    • 感谢问题在 application.yml 名称中我有一个错误的名称 "applicationt.yml" ,@EnableConfigurationProperties(KeyStoreConfig.class) 解决了问题
    猜你喜欢
    • 2019-04-10
    • 1970-01-01
    • 2019-04-04
    • 2016-09-30
    • 2022-01-13
    • 1970-01-01
    • 2018-10-24
    • 2020-07-21
    • 2017-09-07
    相关资源
    最近更新 更多