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

标签 java spring spring-boot spring-test

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

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

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

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

最佳答案

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

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

关于java - 使用 @TestPropertySource 正确定义测试属性的路径 (Spring Boot 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56933129/

相关文章:

java - 我应该如何在没有 xml 的情况下加载 Spring 的 ApplicationContext 进行单元测试?

java - 是否可以让 Spring 仅实例化继承中的父 bean(而不实例化子 bean)?

java - Spring 状态机错误处理不起作用

java - OSGI bundle 结构以及与 CQ5 中其他 bundle 的通信

java - 两个实体之间的多种不同类型关联 - SpringBoot、PostgreSQL

Java 事件绑定(bind)问题绑定(bind)库

spring - @Inject 和 @Autowired 有什么区别

spring - Prometheus UI,Spring Boot 应用程序的 Grafana 设置

tomcat - Spring Boot 中上下文路径的问题

java - 为我的项目建议一个 Maven 存储库管理器