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

Android 單元測試實例分析:從設定到執行

編輯:Android 開發實例

本文以實例說明 Android 單元測試的用法。在實際開發中,撰寫 Android 軟體的過程需要不斷測試,而 JUnit 測試框架正是正規開發必備的技術。透過 JUnit,我們可以取得元件、模擬發送事件,並檢測程式處理是否正確。單元測試既可以嵌入專案之中,也能作為獨立專案來測試某個具體的目標。

第一步:修改 AndroidManifest.xml

首先在 manifest 中加入以下程式碼:

<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