因为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.
}
答案 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