【问题标题】:How to read generated properties file in Spring Boot integration test?如何在 Spring Boot 集成测试中读取生成的属性文件?
【发布时间】:2016-12-09 10:14:56
【问题描述】:

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

git.commit.id=35ca97298544d4ee6f8a5392211ebaa0d9bdafeb

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

@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 作为类路径的基础。

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

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

【问题讨论】:

  • @PropertySource({"classpath:git.properties"}) 也许。
  • 太棒了!有用。你能把它作为答案,所以我可以接受吗?
  • 还有一些解释为什么它的工作原理也很好:)

标签: java spring maven spring-boot spring-test


【解决方案1】:

默认情况下,测试运行程序会查找与测试文件夹相关的资源。例如,当git.properties 文件存在于src/test/resources 中时,它也应该可以工作。

@PropertySource({"classpath:git.properties"}) 告诉从整个类路径中查找源代码。

【讨论】:

    猜你喜欢
    • 2017-07-12
    • 2018-10-30
    • 1970-01-01
    • 2018-08-03
    • 2020-02-25
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多