2012-02-16 99 views
2

我試圖從在Eclipse中正在開發中,像這樣的應用程序運行JUnit測試:編程以外的Eclipse項目的運行JUnit測試

JUnitCore junitCore = new JUnitCore(); 
ClassLoader cl = Main.class.getClassLoader(); 
Class<?> test = cl.loadClass("test.TestCase1"); 
Result r = junitCore.run(test); 

這運行正常,但如果測試用例需要使用一些文件,我得到一個FileNotFoundException。在Eclipse項目中運行相同的測試,測試沒有這樣的錯誤。我認爲這是因爲我的JVM的工作目錄(在user.dir屬性中定義)不同於Eclipse項目。據我所知,我不能在正在運行的JVM中更改user.dir

我該怎麼做才能改變這種行爲?我唯一的選擇是使用與Eclipse項目相同的工作目錄來啓動新的JVM嗎?如果是這樣,我該怎麼做,最好不要使用像Ant這樣的工具?

編輯: 這是一個通過了Eclipse項目測試的例子,併產生FileNotFoundException當我編程方式運行,它的項目之外:

@Test 
public void test() throws Exception { 
    FileInputStream fstream = new FileInputStream("test1.txt"); 
    DataInputStream in = new DataInputStream(fstream); 
    BufferedReader br = new BufferedReader(new InputStreamReader(in)); 
    assertEquals("file content", br.readLine()); 
} 
+0

您能否顯示加載您的文件的代碼片段? – Anton 2012-02-16 10:11:39

+0

@Umar你的意思是加載文件的測試示例?我會爲你編輯它。 – aperez 2012-02-16 10:35:08

+0

只是好奇地想知道,爲什麼你想寫一個應用程序來運行junit,當你在eclipse中默認有junit插件? – 2012-02-16 15:33:27

回答

0

試試這個代碼

new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("filename"))); 

如果你的文件和java類在同一個目錄下,它應該被加載。

更新

在這種情況下,嘗試指定工作目錄當您運行JUnits測試

-Duser.dir=somedir 
+0

謝謝你的回答。不幸的是,我無法更改項目源代碼,包括測試。 – aperez 2012-02-16 11:04:37

0

嘗試檢索當前目錄JUnit測試中,然後創建一個新的文件瀏覽到test1.txt

String currentDirectory = new File("").getAbsolutePath(); 

FileInputStream fstream = new FileInputStream(currentDirectory+"\\XYZ\\test1.txt"); 
相關問題