如何在测试时从@BeforeClass方法中的application.yml文件中获取spring属性

时间:2018-04-10 07:56:40

标签: spring junit

因为Junit中的@BeforeClass方法应该是静态的而静态方法无法访问实例对象,所以我无法使用以下代码来获取spring属性。

@Autowired
private Environment env; 

OR

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

是否还有其他方法可以在Spring Junit测试的application.yml方法中从@BeforeClass访问spring属性?

@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.
}

1 个答案:

答案 0 :(得分:1)

只需使用@Before(而不是@BeforeClass

java测试文件:

@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文件:

spring.path: foo/file.ext

<强>控制台:

sof) path: foo/file.ext