java - 使用 @ActivateProfiles 在 JUnit5 测试中加载不正确的 SpringBoot 属性文件

标签 java spring spring-boot spring-test junit5

我尝试使用 Spring 配置文件名称模式测试具有不同配置文件的配置文件。

这是 Spring 项目的结构:

src/main
    java/foo/bar
        config
            RestClientConfig.java
            ApiProperties.java
    resources
        application.yml
        application-local.yml

application.yml

api:
  authentication-hash: fds456f4ds6f
  rest-api-uri: https://example.org/api

application-local.yml

api:
  authentication-hash: xxxxxxxxx
  rest-api-uri: https://localhost:8081/api

ApiProperties.java

@Configuration
@ConfigurationProperties(prefix = "boond")
@Data
public class BoondProperties {

    @ToString.Exclude // confidentiel
    private String authenticationHash;
    private URI restApiUri;

}

剩余模板配置

@Configuration
public class RestClientConfig {

    private final ApiProperties apiProperties;

    public RestClientConfig(apiProperties apiProperties) {
        this.apiProperties = apiProperties;
    }

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {

        builder.defaultHeader("Authorization", "Basic " +
                apiProperties.getAuthenticationHash());
        builder.uriTemplateHandler(
                new DefaultUriBuilderFactory(apiProperties.getRestApiUri().toString()));
        return builder.build();
    }

}

当我使用 Junit5 运行以下单元测试时,从 application.yml 而不是 application-local.yml 加载属性

@SpringBootTest
@ActiveProfiles("local")
class RestClientConfigTest {
    @Autowired
    RestClientConfig restClientConfig;
    @Autowired
    RestTemplateBuilder restTemplateBuilder;

    @Test
    void rest_client_should_be_able_to_contact_api() {
        RestTemplate apiRestTemplate = restClientConfig.restTemplate(restTemplateBuilder);
        ResponseEntity<String> dictionary = apiRestTemplate.getForEntity("/api/dictionary", String.class);
        assertEquals("OK", dictionary);
    }
}

最佳答案

基于documentation特定于配置文件的 yaml 配置的完成方式有所不同。这里遵循的约定适用于 .properties 文件。

请参阅共享文档

关于java - 使用 @ActivateProfiles 在 JUnit5 测试中加载不正确的 SpringBoot 属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60081575/

相关文章:

java - 从数组 vector 中创建一个元素总和等于数字 k 的数组

Spring Boot 测试失败, 'No bean named ' webHandler'可用'

java - 为什么我从 hello world SpringBoot 收到 WhiteLabel 错误?

java - 使用 hibernate.hbm2ddl.import_files 执行 sql 脚本时出错?

java - 初学者java编程if-else语句低效代码

java - JMeter Beanshell 整数错误

java - 如何在 Spring 中注册自定义类型转换器?

java - 使用 RestController 注释找不到 HTTP 404

java - 使用SVN作为Spring Cloud Config服务器时出错

spring-boot - Liberty Spring Boot 与 Spring Boot