Youssouf Maiga
Youssouf Maiga

Reputation: 7821

Elegant way to init or inject string into a static field beforeClass (JUNIT) from spring configuration?

The annotation @Value("${my.field}") work well if you want to inject data into a non static field.

In my case, I'm building test for my spring boot application. I'm using Junit. I have some task to do @BeforeClass and I need some properties from spring application configuration. I'm looking for a elegant way to get my properties.

Upvotes: 2

Views: 426

Answers (1)

Daniel Olszewski
Daniel Olszewski

Reputation: 14401

You can load the properties file in the static setup method on your own and select the values needed in your tests. For some, it might be less convenient than injection with @Value, but it will do the trick.

public class SomeTestClass {

    private static String myProperty;

    @BeforeClass
    public static void setUpClass() throws Exception {
        Properties prop = new Properties();
        prop.load(new FileInputStream("src/main/resources/application.properties"));
        myProperty = prop.getProperty("your.property.key");
    }

    @Test
    public void shouldLoadProperty() throws Exception {
        assertEquals("expectedValue", myProperty);
    }

}

Upvotes: 1

Related Questions