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

J2ME 單元測試利器 j2meunit 實戰指南:從 Eclipse 整合到真機測試完整流程

     編輯:Java 程式設計入門

前言

J2ME 缺乏 Reflection API,傳統 JUnit 無法自動發現測試。j2meunit (17KB, 開源) 移植 JUnit 核心機制至 J2ME,支援文本與 MIDlet 兩種測試介面,讓單元測試進入真機成為可能。

一、環境建置 (Eclipse + EclipseME)

  1. 下載 j2meunit,解壓取得 j2meunit.jar。
  2. 專案右鍵 Properties → Java Build Path → Libraries → Add External JARs 加入 jar。

二、撰寫測試類

繼承架構

public class TestOne extends j2meunit.framework.TestCase {
    // 必須提供此建構子供框架回呼
    public TestOne(String name, j2meunit.framework.TestMethod method) {
        super(name, method);
    }

    public void testOne() {
        System.out.println("TestOne.testOne()");
        assertTrue("Should be true", false); // 故意失敗示範
    }

    public void testTwo() {
        System.out.println("TestOne.testTwo()");
        throw new RuntimeException("Exception"); // 例外測試
    }

    // 手動組裝 TestSuite (無 Reflection 需手寫)
    public j2meunit.framework.Test suite() {
        j2meunit.framework.TestSuite ts = new j2meunit.framework.TestSuite();
        ts.addTest(new TestOne("testOne", new j2meunit.framework.TestMethod() {
            public void run(j2meunit.framework.TestCase tc) { ((TestOne)tc).testOne(); }
        }));
        ts.addTest(new TestOne("testTwo", new j2meunit.framework.TestMethod() {
            public void run(j2meunit.framework.TestCase tc) { ((TestOne)tc).testTwo(); }
        }));
        return ts;
    }
}

關鍵機制:每個 TestCase 實例僅綁定一個 TestMethod (單一測試方法),透過匿名類別與建構子實現綁定。切勿在一個 TestMethod 執行多個測試,否則前者失敗會阻斷後續。

三、測試套件彙總

public class TestAll extends j2meunit.framework.TestCase {
    public j2meunit.framework.Test suite() {
        j2meunit.framework.TestSuite ts = new j2meunit.framework.TestSuite();
        ts.addTest(new TestOne().suite());
        ts.addTest(new TestTwo().suite()); // 假設存在 TestTwo
        return ts;
    }
}

四、執行方式

1. 文字介面 (模擬器/桌面 JVM)

public static void main(String[] args) {
    String[] runnerArgs = new String[] { "com.example.TestAll" };
    j2meunit.textui.TestRunner.main(runnerArgs);
}

2. MIDlet 介面 (真機/模擬器) — 核心價值

public class TestRunnerMidlet extends j2meunit.midletui.TestRunner {
    protected void startApp() {
        start(new String[] { "com.example.TestAll" });
    }
}

或在 JAD 加入 J2MEUnitTestClasses: com.example.TestAll, com.example.TestOther 無需修改主類。

五、實測結果

  • 模擬器與真機 (MIDP 1.0) 均正常顯示測試結果 (綠條/紅條、錯誤堆疊)。
  • 真機執行範例耗時 ~401ms。

六、最佳實務建議

  • 測試方法命名以 test 開頭,未來若支援 Reflection 可無縫遷移。
  • 覆寫 setUp()/tearDown() 管理測試夾具。
  • 將單元測試納入日常建構流程,及早發現邏輯錯誤與記憶體洩漏。
  • j2meunit 1.1.1 為當前穩定版,社群較小但功能完整。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved