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

Android 單元測試入門實例分析

編輯:關於 Android 程式設計

本文通過一個簡單實例,帶大家快速上手 Android 的單元測試。在實際開發中,Android 應用需要反覆測試,而 JUnit 是正規開發中的必備技術——它能獲取組件、模擬發送事件並驗證程序處理的正確性。單元測試既可以嵌入項目內部,也可以作為獨立工程針對某個項目進行測試。

第一步:配置 AndroidManifest.xml

首先在清單文件中加入測試相關的庫引用與 instrumentation 配置:

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.lee0000.test" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <uses-library android:name="android.test.runner"/>
</application>
<use-sdk android:minSdkVersion="6"/>
<instrumentation android:name="android.test.instrumentationTestRunner" android:targetPackage="com.lee0000.test" android:label="Tests"/> 
 ***注意:上面 targetPackage 指定的包要和應用的 package 相同。

第二步:編寫測試代碼

一般把待測試的方法命名為 testXXX 的形式。測試時在 Outline(大綱)視圖中選中測試方法,右鍵選擇 Run As → Android Junit Test 即可。

項目結構如下:

AndroidManifest.xml 文件:

 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.lee0000.test" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".JUintTestActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <uses-library android:name="android.test.runner" /> </application> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="com.lee0000.test" android:label="Tests"/> </manifest> 

先定義兩個待測試的方法:

 public class testclass { public void str(String s){ System.out.println(s.substring(6)); } public int add(int a,int b){ return a+b; } } 

測試類一般繼承 AndroidTestCase,測試時針對這兩個方法進行。如果在對應方法中選擇 Run As → Android Junit Test 時出錯,可以右鍵點擊 Test 類,選擇 Run As → Run Configurations,在 Instrumentation runner 中進行相應配置:

 import junit.framework.Assert; import android.test.AndroidTestCase; public class Test extends AndroidTestCase{ public void teststr() throws Exception{ testclass tc = new testclass(); tc.str("null"); } public void testadd(){ testclass tc = new testclass(); int t = tc.add(1, 2); Assert.assertEquals(3, t); } } 

以上就是 Android 單元測試的基本入門流程,希望能對大家的學習有所幫助。

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