Java 如何在Spring Boot集成测试中读取生成的属性文件?
在Spring Boot web应用程序中,我使用Java 如何在Spring Boot集成测试中读取生成的属性文件?,java,spring,maven,spring-boot,spring-test,Java,Spring,Maven,Spring Boot,Spring Test,在Spring Boot web应用程序中,我使用git提交id插件Maven插件生成一个名为git.properties的文件,其中包含所有git提交信息,例如: git.commit.id=35ca97298544d4ee6f8a5392211ebaa0d9bdafeb 此文件直接在target/classes存储库中生成。所以它包含在类路径中。在运行时,通过我的主应用程序类上的注释加载文件: @PropertySource({"git.properties"}) 然后,我可以在我的be
git提交id插件
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
存储库中。我仍然有相同的错误。默认情况下,测试运行程序查找与测试文件夹相关的资源。例如,当git.properties
文件出现在src/test/resources
中时,它也应该工作
@PropertySource({“classpath:git.properties”})
告诉您从整个类路径中查找源。@PropertySource({“classpath:git.properties”})
也许吧。太棒了!它起作用了。你能把它作为一个答案,这样我就可以接受它了吗?如果你能解释一下它为什么会起作用,那就好了:)