首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

JUnit 快速上手教學

     編輯:Java 相關知識

Eclipse 專案配置 JUnit

  1. 專案右鍵 → Properties → Java Build Path → Libraries。
  2. 點擊 Add External JARs,選擇 JUnit JAR 檔案。
  3. 在欲測試的類別上右鍵 → New → JUnit Test Case 即可開始。

基本使用流程

  1. 建立測試類別:繼承 junit.framework.TestCase。
  2. 撰寫測試方法:簽名為 public void testXxx()。
  3. 編譯:編譯測試類別。
  4. 執行:啟動 JUnit Test Runner(文字或圖形介面)。
    • 圖形介面:java junit.swingui.TestRunner TestClassName
    • 文字介面:java junit.textui.TestRunner TestClassName

程式碼範例

最簡單測試

import junit.framework.TestCase;
public class TestSample extends TestCase {
    public void testMethod1() {
        assertTrue(true);
    }
}

使用 setUp 與 tearDown

import junit.framework.TestCase;
public class TestSample extends TestCase {
    protected void setUp() {
        // 初始化測試環境
    }
    public void testMethod1() {
        assertTrue(true);
    }
    protected void tearDown() {
        // 清理測試環境
    }
}

執行順序:setUp → testXxx → tearDown。

Failure 與 Exception 的區別

  • Failure(預期失敗):斷言失敗(如 assertFalse(true))或主動呼叫 fail()。
  • Exception(非預期錯誤):測試程式運行時拋出的異常(如 NullPointerException),屬於 Runtime 異常。

異常處理範例

public void testMethod1() {
    try {
        boolean b = ...;
        assertTrue(b);
        throw new Exception("This is a test.");
        fail("Unable point."); // 不會執行到
    } catch (Exception e) {
        fail("Yes, I catch u"); // 預期捕獲點
    }
}

組裝 TestSuite 執行多測試

JUnit 採 Composite 模式:Test、TestCase、TestSuite 形成樹狀結構。自訂 suite() 靜態方法組裝測試套件:

import junit.framework.Test;
import junit.framework.TestSuite;
public class TestAll {
    public static Test suite() {
        TestSuite suite = new TestSuite("Running all tests.");
        suite.addTestSuite(TestCase1.class);
        suite.addTestSuite(TestCase2.class);
        return suite;
    }
}

執行方式同單一 TestCase。優點:靈活管理擴展、可從任意節點開始執行。

整合 Ant 自動化測試

使用 JUnit 提供的 Ant Task:

  • <junit>:定義任務
  • <batchtest>:批次執行多個 TestCase
  • <test>:執行單一 TestCase
  • <formatter>:定義輸出格式(brief、xml)
  • <junitreport> + <report>:生成 HTML 報告

Ant 建構檔片段

<junit printsummary="yes" haltonfailure="no">
  <classpath>
    <path refid="classpath"/>
    <pathelement location="${dist.junit}"/>
  </classpath>
  <formatter type="brief" usefile="false"/>
  <formatter type="xml"/>
  <batchtest todir="${doc.junitReport}">
    <fileset dir="${dist.junit}" includes="**/*Test.class" />
  </batchtest>
</junit>
<junitreport todir="${doc.junitReport}">
  <fileset dir="${doc.junitReport}">
    <include name="TEST*-*.xml"/>
  </fileset>
  <report format="frames" styledir="${junit.styleDir}" todir="${doc.junitReport}"/>
</junitreport>

編寫優質 TestCase 檢查清單

  1. 測試獨立性:一 TestCase 測一物件,一 TestMethod 測一方法。
  2. 方法命名清晰。
  3. 斷言附帶失敗說明訊息。
  4. 覆蓋所有可能失敗點(頻繁修改的方法、手寫 getter/setter)。
  5. setUp/tearDown 僅含共用邏輯。
  6. 測試代碼與產品代碼同套件、不同目錄結構,便於存取 protected 成員與管理發布。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved