如何定义@TestPropertySource(location)?

时间:2019-07-23 10:44:08

标签: unit-testing spring-boot

我正在尝试在测试包中添加test.properties文件。 结构是

test->java->  -> test.java
              -> resource -> test.properties

我的命令是

   @RunWith(SpringRunner.class)
    @ContextConfiguration(classes = Publish.class)
    @TestPropertySource(locations = "classpath:/src/test/java/resources/test.properties")
    public class Test {


...
}

但是我总是一直得到这个

java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: java.lang.IllegalStateException: Failed to add PropertySource to Environment
Caused by: java.io.FileNotFoundException: class path resource [/src/test/java/resources/test.properties] cannot be opened because it does not exist

我还有其他几种变体,但仍然出现此错误,我该如何解决呢?

其他变体:

 @TestPropertySource(locations = "classpath:/test.properties")

 @TestPropertySource(locations = "classpath:/resources/test.properties")

 @TestPropertySource(locations = "classpath:test.properties")

问了另一个类似的问题,但我似乎无法解决我的问题stackOverflow Question

1 个答案:

答案 0 :(得分:1)

应该是

 @TestPropertySource(locations = "classpath:/yourPackage/thatContainResource/test.properties")

src不在运行时,也不是类路径的一部分。

但是最重要的是,您的目录结构是错误的。 resources应该像这样java旁边:

enter image description here

通过像您一样将资源放入资源中,它们被过滤掉了。