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

Android 單元測試入門:AndroidTestCase 完整設定教學

編輯:關於 Android 程式設計

Android 專案的開發過程離不開持續測試。使用 JUnit 測試框架可以說是正規 Android 開發的基本功——它能取得元件、模擬發送事件,並驗證程式處理結果是否正確。

舉個例子:想驗證自定義類別中的某個方法是否正確,只要在單元測試中建立該類別的物件,給入合適的參數呼叫方法,再比對回傳值即可。這種「給定輸入、檢查輸出」的模式,能把 bug 攔在編譯階段之後、上線之前。

四個步驟完成設定

  1. 建立一個類別並繼承 AndroidTestCase,這個類別就是測試類別。
  2. 在 AndroidManifest.xml 中宣告 <instrumentation> 節點,把單元測試庫引入專案。
  3. 在 <application> 中宣告 <uses-library /> 節點。
  4. 點擊測試方法名稱,右鍵選擇 Run As → Android JUnit Test 執行。

測試類別範例

public class AndroidTestCaseDemo extends AndroidTestCase {

    private static final String TAG = "Android JUnit Test";

    public void test1() {
        Log.d(TAG, "test1 run");
    }

    public void test2() {
        Log.d(TAG, "test2 run");
    }
}

注意方法命名必須以 test 開頭,且帶有 public void 修飾、不接受參數,JUnit 才能透過反射找到並執行它。

清單文件配置

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.test.androidtestcasedemo"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <!-- 引入單元測試庫 -->
    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.test.androidtestcasedemo" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

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

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

兩個關鍵設定說明

android:name="android.test.InstrumentationTestRunner" 是固定的,它指定測試執行器;android:targetPackage 則要填寫被測試的專案套件名稱,也就是測試類別所在的包,這裡是 com.test.androidtestcasedemo。

<uses-library android:name="android.test.runner" /> 是告訴系統在執行時載入測試相關的函式庫,少了這行會在啟動階段就失敗。

補充:AndroidTestCase 能給你什麼

相較於純 JUnit 的 TestCase,AndroidTestCase 額外提供了 getContext() 取得測試專案的 Context、getTargetContext() 取得被測應用的 Context,方便驗證資源讀取、SharedPreferences 讀寫等行為。它也內建了 assert... 系列與 AndroidTestCase.assertActivityRequires... 等輔助方法。

需要注意的是,這個方式屬於較早期的做法,測試執行綁在裝置或模擬器上,速度偏慢。若只是驗證純 Java 邏輯,建議把類別剝離對 Android 框架的依賴,改用 src/test 下的本地 JUnit 測試(速度更快);需要 Context 的部分則可考慮 AndroidJUnit4 或後續的 instrumentation 測試框架。

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