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

Android 學習筆記:應用單元測試實例分析

編輯:關於 Android 程式設計

本文結合學習筆記的形式,梳理 Android 應用中單元測試的完整實現步驟,供大家參考。

第一步:配置 AndroidManifest.xml

在清單文件中加入以下兩段代碼:

 <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.pccw" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <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> <!—添加代碼1--> <uses-library android:name="android.test.runner"/> </application> <!—添加代碼2--> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.pccw" android:label="aaa"/> </manifest> 

要點說明:

1. <uses-library android:name="android.test.runner"/> 用於把單元測試框架的一些依賴庫引入進來。

2. <instrumentation ... /> 用於配置單元測試框架的啟動裝置,啟動裝置有多個類可選,一般情況下使用這一個即可。

3. targetPackage 與上面的 package 相同,代表單元測試框架和當前應用處於同一個進程中。

第二步:編寫業務邏輯(待測試模塊)

 public class PersonService { public void save(String name){ String sub = name.substring(6); } public int add(int a, int b){ return a+b; } } 

第三步:編寫單元測試代碼

 public class PersonServiceTest extends AndroidTestCase { public void testSave() throws Exception { PersonService service = new PersonService(); service.save(null); } public void testAdd() throws Exception { PersonService service = new PersonService(); int result = service.add(1, 2); Assert.assertEquals(3, result); } } 

第四步:運行測試

打開 Eclipse 的 Outline 窗口,會列出測試類的所有方法:

想測試哪個方法,就在該方法上右鍵選擇 Run As → Android JUnit Test。若存在異常或錯誤,會呈現如下情況:

若測試正常,則顯示如下:

以上就是應用單元測試的完整流程,希望對大家的 Android 學習有所幫助。

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