从测试yml文件中读取值

问题描述 投票:0回答:1

我有一个带有测试 YAML 文件的 Spring Boot 文件

application-test.yml
位于
src/test/resources
:

keycloak:
  endpoint: https://test.org

在 JUnit 测试中,我尝试使用以下方法读取值:

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;

@PropertySource("classpath:application-test.yml")
public class KeycloakConnectionTest {

    @Value("${keycloak.endpoint}")
    private String ENDPOINT;

    @Test
    void connectionTest() {
        String format = String.format("grant_type=%s&client_id=%s&username=%s", GRANT_TYPE......);
        System.out.println(format);
    }
}

当我运行测试时,我得到输出:

grant_type=null

你知道为什么我得到空值吗?

spring-boot junit junit5 spring-boot-test
1个回答
0
投票

注释

@PropertySource
默认情况下不会加载YAML文件,如文档中所述(强调我的):

YAML 文件无法使用

@PropertySource
@TestPropertySource
注解加载。因此,如果您需要以这种方式加载值,则需要使用属性文件。

我建议覆盖

application.yml
中的
src/test/resources
或在
test
配置文件下运行测试,以防使用
application-test.yml
,只要 Spring Boot 自动检测特定于配置文件的配置即可。

© www.soinside.com 2019 - 2024. All rights reserved.