Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 AndroidTestCase 進行 Android 單元測試

編輯:關於 Android 程式設計

除了 InstrumentationTestCase,AndroidTestCase 同樣可以用來做 Android 單元測試。兩者都是 junit.framework.TestCase 的子類,但代表的方向不同。使用 AndroidTestCase 大致分為三個步驟:

1. 撰寫自己的 test case,並讓它繼承 AndroidTestCase。
2. 定義 TestSuite 類別來管理這些 test case。
3. 定義 TestRunner 來執行測試。

相關的類別與介面

AndroidTestCase
Android 的測試案例要從這個類別派生,而不是直接繼承 junit.framework.TestCase。兩者最主要的差別在於 AndroidTestCase 提供了 getContext() 取得目前的上下文物件——這在 Android 測試中很重要,因為大量 API 都需要 Context。

主要成員:

· setUp():建立測試環境的初始狀態(fixture),例如開啟網路連線。
· tearDown():清除測試環境,例如關閉網路連線。
· testAndroidTestCaseSetupProperly():內建的自我檢查。

TestSuite(套件 junit.framework)
一個 TestSuite 就是多個 test case 的集合,用來更有組織地管理測試。

主要成員:

· void addTest(Test test):把單一測試加入集合。
· void addTestSuite(Class testClass):把指定類別中的所有測試加入集合。

TestSuite suite = new TestSuite();
suite.addTest(new MathTest("testAdd"));           // 逐一加入
suite.addTest(new MathTest("testDivideByZero"));

// 也可以一次加入整個測試類別
suite.addTestSuite(MathTest.class);

TestListener(套件 junit.framework)
這是監聽測試進度的介面,共四個方法:

· addError(Test test, Throwable t):發生錯誤。
· addFailure(Test test, AssertionFailedError t):發生失敗。
· endTest(Test test):一個測試結束。
· startTest(Test test):一個測試開始。

AndroidTestRunner
繼承自 junit.runner.BaseTestRunner,但它沒有提供任何 UI,連基本 console 介面都沒有。因此若想清楚看到測試結果,必須自行處理來自 test runner 的回呼函式(透過 TestListener)。主要方法有 setTest()、runTest()、addTestListener()、setContext()。

使用 AndroidTestRunner 時,需在 manifest 中加入:

<uses-library android:name="android.test.runner" />

實作範例

1. 撰寫 test case:MathTest.java

package com.ut.prac;

import android.test.AndroidTestCase;
import android.util.Log;

public class MathTest extends AndroidTestCase {
    protected int i1;
    protected int i2;
    static final String LOG_TAG = "MathTest";

    public void setUp() {
        i1 = 2;
        i2 = 3;
    }

    public void testAdd() {
        Log.d(LOG_TAG, "testAdd");
        assertTrue(LOG_TAG + "1", ((i1 + i2) == 5));
    }

    public void testAndroidTestCaseSetupProperly() {
        super.testAndroidTestCaseSetupProperly();
        Log.d(LOG_TAG, "testAndroidTestCaseSetupProperly");
    }
}

2. 定義 test suite:ExampleSuite.java

package com.ut.prac;

import junit.framework.TestSuite;

public class ExampleSuite extends TestSuite {
    public ExampleSuite() {
        addTestSuite(MathTest.class);
    }
}

命名慣例與注意事項

JUnit 3 風格的測試以「方法名稱是否以 test 開頭」來識別測試項目,因此測試方法請一律命名為 testXxx,且不帶參數。若需要在每個測試前準備資料,就放在 setUp();需要善後清理則放 tearDown()。最後記得補上 TestRunner 並掛上 TestListener,否則測試會執行卻看不到任何輸出。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved