我試圖從在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());
}
您能否顯示加載您的文件的代碼片段? – Anton 2012-02-16 10:11:39
@Umar你的意思是加載文件的測試示例?我會爲你編輯它。 – aperez 2012-02-16 10:35:08
只是好奇地想知道,爲什麼你想寫一個應用程序來運行junit,當你在eclipse中默認有junit插件? – 2012-02-16 15:33:27