Why does @Value returns null for key in @TestPropertySource, for static variable

57 views Asked by At

I'm unit testing code that gets its setup from environment variables. The problem I'm seeing is that @Value() is not finding the keys.

@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);
    }
}
2

There are 2 answers

1
200ok On

if you don't set locations property in @TestPropertySource, @TestPropertySource finds properties file based on the class to which the @TestPropertySource was added

for example, if your class is in "com.demo" package, there must be a "com.demo.xxx.properties" file on the classpath

so you need to do add properties files where MyUnitTest is located or add locations property

example

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

    @BeforeAll
    static void setUp() {
        // ...
    }
}
0
wybourn On

You can't use @Value on a static field.