Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 學習筆記:單元測試實例完整解析

編輯:Android 開發實例

本文以實例方式,完整說明如何在 Android 專案中設定並執行單元測試。測試是開發流程中不可或缺的一環,透過 JUnit 框架能有效驗證程式的正確性。

第一步:修改 AndroidManifest.xml

在 manifest 中加入以下兩段設定:

 <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 android:name="android.test.InstrumentationTestRunner" .../> 代表設定測試框架的啟動裝置。啟動器有多種可選,一般情況下使用上面這一個即可。

3. 其中 targetPackage 要與上面的 package 相同,代表測試框架與目前的 App 處於同一個進程中。

第二步:撰寫待測試的業務邏輯

 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