Reputation: 3742
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
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