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

Android 學習筆記:使用 JUnit 對應用進行單元測試

編輯:關於 Android 程式設計

在實際開發中,撰寫 Android 軟體的過程需要不斷測試。使用 JUnit 測試框架是正規 Android 開發的必備技術,它能取得元件、模擬發送事件,並檢測程式處理的正確性。

第一步:在 AndroidManifest.xml 中加入測試設定

首先在 application 節點加入 uses-library,並在 manifest 中加入 instrumentation 設定:

<application android:icon="@drawable/icon" android:label="@string/app_name">
  <uses-library android:name="android.test.runner" />
</application>
<instrumentation android:name="android.test.InstrumentationTestRunner"
  android:targetPackage="cn.itcast.action" android:label="Tests for My App" />

第二步:撰寫單元測試程式碼

建立測試類別並繼承 AndroidTestCase,選擇要測試的方法後右鍵執行「Run As → Android JUnit Test」:

package com.credream.junit;
import junit.framework.Assert;
import com.credream.service.PersonServices;
import android.test.AndroidTestCase;
public class PersonServiceTest extends AndroidTestCase {
  public void testSave() throws Exception {
    // 這個方法出錯時,會拋出異常給測試框架
    PersonServices services = new PersonServices();
    services.save(null);
  }
  public void testAdd() throws Exception {
    PersonServices services = new PersonServices();
    int result = services.add(1, 2);
    Assert.assertEquals(3, result);
  }
}

被測試的類別

以下是簡單的被測試類別,save 方法故意示範會拋出異常的情況,add 方法則回傳兩數之和:

package com.credream.service;
public class PersonServices {
  public void save(String username){
    String sub = username.substring(6);
  }
  public int add(int a, int b) {
    return a + b;
  }
}

獨立測試專案

測試也可以另外建立一個獨立的專案以便重複使用:選擇「New → Other → Android Test Project」,即可建立一個專用的測試專案。

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