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

  什么是Instrumentation?

  一般在開發(fā)Android程序的時候,需要寫一個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>  

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

  “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.“

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

  那么如何加載它呢,首先要在manifest文件中加入一行關(guān)于Instrumentation的聲明。比如Android Api Demos中的測試?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命令手工完成),然后安裝到虛擬機上(用adb install命令)。之后可以利用命令行的方式來加載你的單元測試了。在Android Shell中加載一個Instrumentation的方法是利用以下命令:

  adb shell am instrument –w XXXXXX

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

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

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

wordend 相關(guān)閱讀:

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

  如何在Android中利用Instrumentation來進行測試?

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

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