niaomingjian
niaomingjian

Reputation: 3742

How to get spring properties from application.yml file in @BeforeClass method when testing

Because @BeforeClass method in Junit should be static and static methods couldn't access instance objects, I couldn't use the following code to get spring properties.

@Autowired
private Environment env; 

OR

@Value("${spring.path}")
private String path; 

Are there other ways to access spring properties from application.yml in @BeforeClass method of Spring Junit Test?

@BeforeClass
public static void test() {
    // I want to access path or env variable here.
    // Generally, it's impossible to access instance variables in static method
    // So my question is how to access spring properties from here.

    // In the case, I'd like to copy a file to spring.path folder for testing.
}

Upvotes: 5

Views: 1010

Answers (1)

Stéphane GRILLON
Stéphane GRILLON

Reputation: 11882

Just use @Before (instead of @BeforeClass)

java test file:

@RunWith(SpringRunner.class)
@SpringBootTest
public class SofTests {
    @Autowired
    private Environment env;

    @Value("${spring.path}")
    private String path;

    @Before
    public void sof() {
        System.out.println("sof) path: " + path);
    }

}

src/test/resources/application.yml file:

spring.path: foo/file.ext

Console:

sof) path: foo/file.ext

Upvotes: 2

Related Questions