如何在 Spring 引导集成测试中读取生成的属性文件?

How to read generated properties file in Spring Boot integration test?

在 Spring 启动 Web 应用程序中,我使用 git-commit-id-plugin Maven 插件生成一个名为 git.properties 的文件,其中包含所有 git 提交信息,例如:

git.commit.id=35ca97298544d4ee6f8a5392211ebaa0d9bdafeb

此文件直接在 target/classes 存储库中生成。所以它包含在 class 路径中。在 运行 时,文件通过我的主应用程序上的注释加载 class :

@PropertySource({"git.properties"})

然后我可以在我的 bean 中使用表达式来获取 git.properties 文件中包含的属性的值:

@Value("${git.commit.id}")
private String gitCommitIdFull; // will contain "35ca97298544d4ee6f8a5392211ebaa0d9bdafeb"

当 运行正常运行应用程序时,一切都很好。

但我现在正在尝试 运行 一些 运行 与 :

的集成测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleSearchDAOTest {
    //tests here...
}

我得到以下异常:

java.lang.IllegalStateException: Failed to load ApplicationContext
(...)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException:
Failed to parse configuration class [ch.cscf.mds.MdsApiApplication]; 
nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/git.properties]

显然,测试的方式是 运行,它们似乎不使用 target/classes 作为 class 路径的基础。

它有什么用?如何让这些测试的 运行 时间知道 target/classes/git.properties 文件?

我试图将 git.properties 文件生成到 src/main/resources 目录而不是 target/classes 存储库中。我仍然有同样的错误。

测试运行程序默认查找与测试文件夹相关的资源。例如,当 git.properties 文件出现在 src/test/resources 中时,它也应该有效。

@PropertySource({"classpath:git.properties"}) 指示从整个类路径中查找源。