簡體   English   中英

在Eclipse項目之外以編程方式運行JUnit測試

[英]Running JUnit tests programmatically outside of their Eclipse project

我試圖從正在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());
}

試試這個代碼

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

如果您的文件與java類位於同一目錄中,則應將其加載。

更新資料

在這種情況下,請在運行JUnits測試時嘗試指定工作目錄。

-Duser.dir=somedir

嘗試檢索您的JUnit測試所在的當前目錄,然后創建一個新文件,導航到test1.txt

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

FileInputStream fstream = new FileInputStream(currentDirectory+"\\XYZ\\test1.txt");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM