为什么@Value对于静态变量@TestPropertySource中的key返回null

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

我正在对从环境变量获取设置的代码进行单元测试。我看到的问题是 @Value() 找不到键。

@ContextConfiguration
@TestPropertySource(
    properties = {
        "foo=bar",
        "baz=qux"
    })
@Testcontainers
class MyUnitTest {
    @Value("${foo}")
    private static String theFoo;

    @BeforeAll
    static void setUp() {
        // in the logs this displays as null
        LOG.info("foo={}", theFoo);
    }
}
java spring unit-testing junit5
1个回答
0
投票

如果你没有在

@TestPropertySource
中设置locations属性,
@TestPropertySource
根据添加了
@TestPropertySource
的类查找属性文件

例如,如果您的类位于“com.demo”包中,则类路径上必须有一个“com.demo.xxx.properties”文件

因此您需要添加

MyUnitTest
所在位置的属性文件或添加位置属性

示例

@ContextConfiguration
@TestPropertySource(
    locations = "/xxx.properties",
    properties = {
        "foo=bar",
        "baz=qux"
    }) //properties will override xxx.properties value
@Testcontainers
class MyUnitTest {
    @Value("${foo}")
    private static String theFoo;

    @BeforeAll
    static void setUp() {
        // in the logs this displays as null
        LOG.info("foo={}", theFoo);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.