Java 使用@TestPropertySource(Spring Boot 2)正确定义测试属性的路径
我的SpringBoot2测试文件夹中有以下层次结构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 =
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
文件一样)。