2016-12-09 57 views
1

在春季啓動Web應用程序,我用的是git-commit-id-plugin Maven插件生成一個名爲git.properties文件,包含所有的git的承諾信息,e.g:如何在Spring Boot集成測試中讀取生成的屬性文件?

git.commit.id=35ca97298544d4ee6f8a5392211ebaa0d9bdafeb 

此文件在target/classes庫中直接生成。所以它包含在classpath中。在運行時,文件是通過註釋裝上我的主應用程序類:

@PropertySource({"git.properties"}) 

然後我可以使用表達式在我的豆子得到包含在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存儲庫。我仍然有同樣的錯誤。

+0

'@PropertySource({「classpath:git.properties」})'也許。 – Vaelyr

+0

非常好!有用。你可以把它作爲答案,我可以接受嗎? –

+0

有些解釋爲什麼它的作品也會很好:) –

回答

3

默認情況下,測試運行器會查找與測試文件夾相關的資源。例如,當git.properties文件將出現在src/test/resources中時,它也應該起作用。

@PropertySource({"classpath:git.properties"})告訴查找整個類路徑的來源。

相關問題