Spring Boot 从测试YML文件读取值

oxf4rvwz  于 2023-06-22  发布在  Spring
关注(0)|答案(1)|浏览(167)

我有一个Sping Boot 文件,其中测试yml文件application-test.yml位于src\test\resources

application-test.yml

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
你知道为什么我会得到null值吗?

pvabu6sv

pvabu6sv1#

注解@PropertySource默认情况下不加载文档中所述的YAML文件(强调我的):
无法使用@PropertySource@TestPropertySource注解加载YAML文件。因此,如果需要以这种方式加载值,则需要使用属性文件。
我建议在src/test/resources中覆盖application.yml,或者在使用application-test.yml的情况下在test配置文件下运行测试,只要Sping Boot 自动检测特定于配置文件的配置。

相关问题