2016-11-13 24 views
4

在單元測試(junit的)我有這樣的代碼中使用Java 8.如何讀取運行時創建的文件?

基本上,:

callSomeCode(); 
assertTrue(new File(this.getClass().getResource("/img/dest/someImage.gif").getFile()).exists()); 

callSomeCode(),我有這樣的:

InputStream is = bodyPart.getInputStream(); 
File f = new File("src/test/resources/img/dest/" + bodyPart.getFileName()); //filename being someImage.gif 
FileOutputStream fos = new FileOutputStream(f); 
byte[] buf = new byte[40096]; 
int bytesRead; 
while ((bytesRead = is.read(buf)) != -1) 
    fos.write(buf, 0, bytesRead); 
fos.close(); 

第一次測試運行,this.getClass().getResource("/img/dest/someImage.gif")返回null雖然該文件是很好創建。

第二次(當第一次測試運行期間已經創建了該文件,然後剛剛被覆蓋),它是非空的,測試通過。

如何讓它第一次工作?
我應該在IntelliJ中配置特殊設置以自動刷新文件所在的文件夾?

請注意,我有這樣的基本結構行家:

--src 
----test 
------resources 
+1

http://stackoverflow.com/a/1011126/1587791 – nakano531

回答

2

由於評論由nakano531指出 - 你的問題是不是與文件系統,但用的類路徑。您試圖通過調用getClass().getResource(...)方法使用類加載器來讀取文件,而不是使用直接訪問文件系統的類來讀取文件。

例如,如果你寫你的測試是這樣的:

callSomeCode(); 
File file = new File("src/test/resources/img/dest/someImage.gif"); 
assertTrue(file.exists()); 

你不會有你現在遇到的問題。

你的另一個選擇是實現從鏈路nakano531提供的解決方案:https://stackoverflow.com/a/1011126/1587791

+0

事實上,我甚至會說明顯。謝謝 ;) – Mik378