您的位置:軟件測(cè)試 > 開源軟件測(cè)試 > 開源單元測(cè)試工具 > junit
Android 下junit 單元測(cè)試
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2014/1/14 14:47:00 ] 推薦標(biāo)簽:單元測(cè)試 junit Android

  什么是Instrumentation?

  一般在開發(fā)Android程序的時(shí)候,需要寫一個(gè)manifest文件,其結(jié)構(gòu)是:

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".TestApp" android:label="@string/app_name">
……
</activity>
</application>  

  這樣,在啟動(dòng)程序的時(shí)候會(huì)先啟動(dòng)一個(gè)Application,然后在此Application運(yùn)行過程中根據(jù)情況加載相應(yīng)的Activity,而 Activity是需要一個(gè)界面的。但是Instrumentation并不是這樣的。你可以將Instrumentation理解為一種沒有圖形界面 的,具有啟動(dòng)能力的,用于監(jiān)控其他類(用Target Package聲明)的工具類。任何想成為Instrumentation的類必須繼承android.app.Instrumentation。下面是 這個(gè)類的解釋:

  “Base class for implementing application instrumentation code. When running with instrumentation turned on, this class will be instantiated for you before any of the application code, allowing you to monitor all of the interaction the system has with the application. An Instrumentation implementation is described to the system through an AndroidManifest.xml's tag.“

  對(duì)于單元測(cè)試,我們需要認(rèn)真了解的是android.test.InstrumentationTestRunner類。這是Android單元測(cè)試的主入口。它相當(dāng)于JUnit當(dāng)中TestRunner的作用。

  那么如何加載它呢,首先要在manifest文件中加入一行關(guān)于Instrumentation的聲明。比如Android Api Demos中的測(cè)試?yán)锏膍anifest是這么寫的(我濾掉了所有的注釋):

 

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.android.apis.tests">

<application>

<uses-library android:name="android.test.runner"/>

</application>

<instrumentation android:name="android.test.InstrumentationTestRunner"

android:targetPackage="com.example.android.apis"

android:label="TestsforApi Demos."/>

</manifest>

  如果用Eclipse的ADT插件(0.8版本以上),也可以用圖形界面來添加,如下圖:

 

  編輯好 manifest,可以打包(build,可以用Eclipse ADT來做,也可以用aapt命令手工完成),然后安裝到虛擬機(jī)上(用adb install命令)。之后可以利用命令行的方式來加載你的單元測(cè)試了。在Android Shell中加載一個(gè)Instrumentation的方法是利用以下命令:

  adb shell am instrument –w XXXXXX

  其中-w是指定Instrumentation類的參數(shù)標(biāo)志。一個(gè)簡(jiǎn)單的例子是:

  adb shell am instrument -w com.android.foo/android.test.InstrumentationTestRunner

  當(dāng)然,也可以利用adb shell先進(jìn)入android命令行模式,再直接寫am instrument –w XXXXXXX。下面將具體介紹如何將根據(jù)需要加載一組單元測(cè)試。

wordend 相關(guān)閱讀:

    MOTODEV初體驗(yàn),高效Android開發(fā)工具
    詳解如何實(shí)現(xiàn)一個(gè)基本的Android用戶界面
    Android應(yīng)用開發(fā)實(shí)戰(zhàn):GPS與加速度傳感器

  如何在Android中利用Instrumentation來進(jìn)行測(cè)試?

  在介紹具體的命令之前,我們先理解一下單元測(cè)試的層次。一組單元測(cè)試可以被組織成若干個(gè)TestSuite。每個(gè)TestSuite包含若干 TestCase(某個(gè)繼承android.jar的junit.framework.TestCase的類)。每個(gè)TestCase又包含若干個(gè) Test(具體的test方法)。

上一頁12345下一頁
軟件測(cè)試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請(qǐng)使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd