Java 使用@TestPropertySource(Spring Boot 2)正确定义测试属性的路径

Java 使用@TestPropertySource(Spring Boot 2)正确定义测试属性的路径,java,spring,spring-boot,spring-test,Java,Spring,Spring Boot,Spring Test,我的SpringBoot2测试文件夹中有以下层次结构 test/ java/ package.name/ SpringBootTest.java resources/ test.properties SpringBootTest的代码如下 @RunWith (SpringRunner.class) @TestPropertySource(locations =

我的SpringBoot2测试文件夹中有以下层次结构

 test/
      java/
           package.name/
                        SpringBootTest.java

       resources/
                 test.properties
SpringBootTest的代码如下

@RunWith (SpringRunner.class)
@TestPropertySource(locations = {"/resources/test.properties"})
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, 
             properties = {"management.port=0"})
public class SwaggerExtractorTest { ... } 
我还尝试将locations={“test.properties”}与位于java类本身旁边的文件以及其他一些路径一起使用,但总是出现错误,类路径资源[…]无法打开,因为它不存在

理想情况下,我希望@TestPropertySource的路径可以放置在测试代码层次结构的不同级别上,而无需更改,即相对于某个顶层


设置此路径的正确方法是什么?

假设您所指的
test/resources
文件夹是您的Maven/Gradle构建使用的
src/test/resources
文件夹

@TestPropertySource(“/test.properties”)
@TestPropertySource(“classpath:test.properties”)
是等效的,它们都应该用于引用类路径根目录中的
test.properties
文件。

这为我修复了它

确保在源中设置了测试资源文件夹。以下是IntelliJ的说明:

  • 单击“项目”选项卡
  • 右键单击项目并选择“打开模块设置”
  • 在“项目设置”下,选择“模块”
  • 在“源”下,确保列出了测试资源文件夹。我的看起来像:

  • 从该位置删除
    /resources/
    。确保
    test.properties
    已移动到
    目标/测试类中。也许问题就在这里……试试:@TestPropertySource(“classpath:test.properties”)@M.Deinum然后它会期望测试文件旁边的文件(相同的类路径)。然而,把它移到那里不会有帮助。出于某种原因,我假设它的前缀是
    classpath:
    (我讨厌星期一)。您应该使用
    类路径:test.properties
    src/test/resources
    是测试类路径的根(就像
    src/test/java
    但是对于
    .java
    文件一样)。