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

Android 測試中 TestSuite 的執行方法

編輯:關於 Android 程式設計

要在 Android 上以 TestSuite 批次執行測試,需要自訂一個繼承自 InstrumentationTestRunner 的 Runner,並在清單檔中註冊。以下記錄完整做法。

一、自訂 TestRunner

public class StartTest extends InstrumentationTestRunner {
    public TestSuite getAllTests() {
        TestSuite suite = new InstrumentationTestSuite(this);
        suite.addTestSuite(TestRunner.class);
        return suite;
    }
}

這裡有三個重點:

1. 類別必須繼承 InstrumentationTestRunner。

2. 方法名稱一定要是 getAllTests(),這是父類的虛方法——一開始沒注意到這點,走了不少冤枉路,特別記下來提醒。

3. 最後要把組好的 TestSuite 回傳。

二、修改 AndroidManifest.xml

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.mobile.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="5" />

    <instrumentation
        android:name="android.test.InstrumentationTestRunner"
        android:targetPackage="com.mobile" />
    <instrumentation
        android:targetPackage="com.mobile"
        android:name="com.mobile.test.StartTest" />
    <!-- 新增的 instrumentation:targetPackage 為被測套件,name 為 TestSuite 的套件.類別 -->

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="android.test.runner" />
    </application>
</manifest>

三、執行測試

在 Eclipse 中右鍵選擇 Run configurations...,勾選「Run all tests in the selected project, or package」,選好測試專案,Instrumentation runner 填你在清單檔設定的 com.mobile.test.StartTest,按下 Run 即可。

也可以用命令列執行:

am instrument -w com.mobile.test/.StartTest

補充一個小技巧:adb shell pm list instrumentation 可以列出裝置上所有已安裝的 instrumentation。

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