【问题标题】:Correctly define path to test properties using @TestPropertySource (Spring Boot 2)使用 @TestPropertySource (Spring Boot 2) 正确定义测试属性的路径
【发布时间】:2019-11-17 20:42:46
【问题描述】:

我的 Spring Boot 2 测试文件夹中有以下层次结构

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

我还尝试将位置 = {"test.properties"} 与位于 java 类本身旁边的文件和其他一些路径一起使用,但它始终是错误 类路径资源 [... ] 无法打开,因为它不存在。

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

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

【问题讨论】:

  • 从该位置删除/resources/。
  • 确保 test.properties 移动到 target/test-classes。也许问题就在那里......
  • 尝试 ::: @TestPropertySource("classpath:test.properties")
  • @M.Deinum 然后它会期望文件在测试文件旁边(相同的类路径)。但是把它移到那里也无济于事。
  • 出于某种原因,我认为它的前缀是classpath:(我讨厌星期一)。你应该使用classpath:test.properties。 src/test/resources 是测试类路径的根(就像 src/test/java 但对于 .java 文件)。

标签: java spring spring-boot spring-test


【解决方案1】:

这为我解决了问题。

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

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

【讨论】:

    【解决方案2】:

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

    @TestPropertySource("/test.properties") 和 @TestPropertySource("classpath:test.properties") 是等价的,两者都应该适用于引用类路径根目录中的 test.properties 文件。

    【讨论】:

      猜你喜欢
      • 2018-09-21
      • 2019-03-20
      • 2018-11-14
      • 2020-01-07
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      相关资源
      最近更新 更多