Spring测试:为什么无法访问application.properties?

Ant*_*arf 3 spring-test spring-boot

我正在构建一个极其简单的 Spring Boot 应用程序。它没有代码,只是一个简单的测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {

    @Value("${my.key}")
    private String key;

    @Test
    public void test() {
        System.out.println(key);
    }
}
Run Code Online (Sandbox Code Playgroud)

my.key是在里面定义的src/main/resources/application.properties(在main/not中test/

测试未通过,因为找不到my.key属性(但如果我将此属性放入其中,src/test/resources/application.properties它就可以工作)

我确信我见过很多 Spring Boot 应用程序,其中测试类从中读取属性/main/resources/application.properties

但在这里它不起作用。

rie*_*pil 5

如果您还在application.properties内添加一个文件src/test/resources,这将“覆盖” 中的文件src/main/resources,因此您在“生产”属性文件中定义的任何键都不会被看到。

因此,要么删除您的application.propertiesinsrc/test/resources以使用您的属性文件src/main/resources,要么在那里定义您的值。