2005年3月1日

如何在 Eclipse 下透過 an _執行 junit 操作?

最近因為更換 IDE 到 IBM Eclipse 平台上,第一次整合 ant 進行 junit 功能測試時 Eclpise 吐出了以下的訊息!

Eclipse 錯誤訊息
BUILD FAILED: E:ProjectsFITELbuild.xml:73: The following error occurred while executing this line:
E:ProjectsFITELant.scriptSendMailTest.xml:4: Could not create task or type of type: junit.
Ant could not find the task or a class this task relies upon.
This is common and has a number of causes; the usual solutions are to read the manual pages then download and install needed JAR files, or fix the build file: - You have misspelt 'junit'. Fix: check your spelling. - The task needs an external JAR file to execute and this is not found at the right place in the classpath. Fix: check the documentation for dependencies. Fix: declare the task. - The task is an Ant optional task and the JAR file and/or libraries implementing the functionality were not found at the time you yourself built your installation of Ant from the Ant sources. Fix: Look in the ANT_HOME/lib for the 'ant-' JAR corresponding to the task and make sure it contains more than merely a META-INF/MANIFEST.MF. If all it contains is the manifest, then rebuild Ant with the needed libraries present in ${ant.home}/lib/optional/ , or alternatively, download a pre-built release version from apache.org - The build file was written for a later version of Ant Fix: upgrade to at least the latest release version of Ant - The task is not an Ant core or optional task and needs to be declared using <taskdef>. - You are attempting to use a task defined using <presetdef> or <macrodef> but have spelt wrong or not defined it at the point of use
Remember that for JAR files to be visible to Ant tasks implemented in ANT_HOME/lib, the files must be in the same directory or on the classpath
Please neither file bug reports on this problem, nor email the Ant mailing lists, until all of these causes have been explored, as this is not an Ant bug.
到 Google 一查,原來不是只有我有這個問題啊!解決的方式網路上很多,不過從這個錯誤訊息也可以推敲出一點端倪:
  1. junit 作業動彈不得,所以透過 junit 所寫的 TestCase 統統無法執行對應的測試。
  2. ant 提醒你可能拼錯 junit 了。
  3. ant 告訴你可能忘了定義指定任務的相關設定。
  4. ant 猜想你可能缺了相關的 .jar 檔。
因為 junit 確定沒有拼錯,而且 junit 還是 ant 內訂支援的任務種類,所以最後的問題應該是出現在 缺了相關的 .jar 檔 上面。
解決方案當然是將欠缺的 .jar 檔補給 Eclipse 中的 ant 囉!預設 Eclipse 使用的是自己的 ant 建置環境(所以會發現如果在 console 下執行 ant 時他就會正常了),所以解決的方式有兩種:
  1. 將 junit.jar 丟到 Eclipse 內建的 ant 環境下。
  2. 將 Eclipse 內建的 ANT_HOME 變數指向系統已建置完成的路徑中。
以下示範如何將 Eclipse 內建的 ANT_HOME 變數指向系統已置的 ANT 環境中:
  1. 點選 Eclipse 選單列上的【 視窗 】->【 喜好設定 】,這會開啟 喜好設定視窗
    開啟喜好設定視窗
  2. 點選 喜好設定視窗 左邊列表的 ANT -> 執行時期
    點選執行時期
  3. 點選畫面右側的 ANT 起始目錄 ,將 ANT_HOME 重新設定到系統已建置好的 ANT 環境上。
    設定 ANT 起始目錄
  4. 如果嫌重新指定 ANT_HOME 很麻煩,那就把 junit.jar 檔案複製到 Eclipse 預設的 ANT_HOME 中。Eclipse 預設的 ANT_HOME 位址
JavaWorld 中有一篇 Eclipse使用技巧分享區:熱鍵、外掛、相關技巧...