正确定义测试属性的路径

正确定义测试属性的路径

本文介绍了使用@TestPropertySource (Spring Boot 2) 正确定义测试属性的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a following hierarchy in my Spring Boot 2 test folder

 test/
      java/
           package.name/
                        SpringBootTest.java

       resources/
                 test.properties

SpringBootTest 有一个类似的代码

SpringBootTest has a code like

@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类本身旁边的文件和其他一些路径一起使用,但它总是错误类路径资源[...] 无法打开,因为它不存在.

I also tried to use locations = {"test.properties"} with the file located just next to the java class itself, and some other paths, but it was always the error class path resource [...] cannot be opened because it does not exist.

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

Ideally I like to have path for @TestPropertySource that I can place on different levels of test code hierarchy without change, that is, relative to some top level.

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

What would be a correct way to set this path?

推荐答案

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

Assuming the test/resources folder you are referring to is the src/test/resources folder used by your Maven/Gradle build...

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

@TestPropertySource("/test.properties") and @TestPropertySource("classpath:test.properties") are equivalent, and both should work for referencing a test.properties file in the root of the classpath.

这篇关于使用@TestPropertySource (Spring Boot 2) 正确定义测试属性的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:45