Android學(xué)習(xí)筆記之如何對(duì)應(yīng)用進(jìn)行單元測(cè)試
開發(fā)環(huán)境:
Win XP + eclipse-jee-helios(版本號(hào)3.6) + ADT(版本10.0.1) + Android SDK(版本10);
模擬器及真機(jī)測(cè)試環(huán)境:Android2.2
在Android軟件的開發(fā)過程中,可以使用Junit測(cè)試框架。在Junit中可以得到組件,可以模擬發(fā)送事件和測(cè)試程序處理的正確性。
第一步:在新建項(xiàng)目中,創(chuàng)建待測(cè)試的業(yè)務(wù)類,在cn.hao.service包中,代碼如下:
package cn.hao.service; //業(yè)務(wù)類,待測(cè)試的兩個(gè)方法 public class PersonaService { public void save(String username){ String sub = username.substring(6); } public int add(int a,int b){ return a+b; } } |
說(shuō)明:對(duì)于save()方法,如果參數(shù)為null,那么這個(gè)方法會(huì)發(fā)生錯(cuò)誤;對(duì)add()方法,我們測(cè)試相加返回的相加結(jié)果是否正確。
第二步:為應(yīng)用引進(jìn)單元測(cè)試環(huán)境
在AndroidManifest.xml中加入如下代碼:
<uses-library android:name="android.test.runner"/>
<instrumentation android:name="android.test.instrumentationTestRunner"
android:targetPackage="cn.hao.JunitTest" android:label="Test for My App" />
引入的位置如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cn.hao.JunitTest" 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="cn.hao.test.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> <uses-library android:name="android.test.runner"/> </application> <instrumentation android:name="android.test.instrumentationTestRunner" android:targetPackage="cn.hao.JunitTest" android:label="App Test" /> </manifest> |
說(shuō)明:在項(xiàng)目中使用單元測(cè)試,就是檢查程序及處理結(jié)果的正確性。
第三步:新建一個(gè)類,測(cè)試業(yè)務(wù)類,代碼如下:
package cn.hao.junit; import junit.framework.Assert; import cn.hao.service.PersonaService; import android.test.AndroidTestCase; public class PersonServiceTest extends AndroidTestCase { public void testSave() throws Exception { PersonaService service = new PersonaService();//new出測(cè)試對(duì)象 service.save(null); } public void testAdd() throws Exception { PersonaService service = new PersonaService(); int actual = service.add(1, 2); Assert.assertEquals(3, actual); } } |
注意:該類需繼承單元測(cè)試框架父類android.test.AndroidTestCase類,測(cè)試方法最好是拋出異常給測(cè)試框架。方法Assert.assertEquals(3, actual)中參數(shù)3是期望(理論上)返回的果,actual是實(shí)際上返回的結(jié)果。
第四步:運(yùn)行測(cè)試類
在大綱OutLine視圖中,右擊測(cè)試方法->Run As->Android Junit Test,會(huì)將項(xiàng)目自動(dòng)部署到模擬器上,測(cè)試的結(jié)果會(huì)以顏色的形式顯示,綠色表示方法正確,否則該方法不正確,Eclipse會(huì)給出詳細(xì)的說(shuō)明,根據(jù)幫助文檔可以查看相應(yīng)的錯(cuò)誤信息。
如測(cè)試上述testSave()方法時(shí),會(huì)給出如下提示:
當(dāng)然,save()從第六位開始取子字符串,但是該方法現(xiàn)在的參數(shù)為null,會(huì)發(fā)生空指針異常。
posted on 2014-09-19 09:55 順其自然EVO 閱讀(293) 評(píng)論(0) 編輯 收藏 所屬分類: 測(cè)試學(xué)習(xí)專欄