編輯:Android 開發實例
本文以實例說明 Android 單元測試的用法。在實際開發中,撰寫 Android 軟體的過程需要不斷測試,而 JUnit 測試框架正是正規開發必備的技術。透過 JUnit,我們可以取得元件、模擬發送事件,並檢測程式處理是否正確。單元測試既可以嵌入專案之中,也能作為獨立專案來測試某個具體的目標。
首先在 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 開發有所幫助。
Android 筆記:自製下拉刷新 ListView 的完整拆解
ListView 是 Android 裡應用最廣的元件之一,功能強大、擴充彈性高,前面幾篇我們陸續玩過分組、拖曳排序、3D 立體、游標、圓角等變形。這次要動手做的是另一個
Android 本地化:打造多語系 App
一款 Android App 可能會在不同國家、不同地區的裝置上被使用。為了讓應用更貼近使用者,App 應該依據裝置所在的語言環境,自動調整文字、數字、檔案等內容的呈現方
Android 載入動畫怎麼做?ProgressBar 轉圈指示器完整說明
使用者按下一顆按鈕後若畫面毫無反應,通常會以為 App 當掉了。這時候一個小小的旋轉動畫,就能把「不確定要等多久」的焦慮大幅降低。Android 的 ProgressBa
MediaPlayer 音訊與視訊播放:搭配 SurfaceView 與 SeekBar 的完整實作
前面的文章把 Android 介面的入門技術介紹得差不多了,相信讀者對常見的 Layout 與 View 都已經有概念。接下來不再談介面,改針對具體功能逐一深入。 本文