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

  如果假設(shè)com.android.foo是你的測試代碼的包的根。當(dāng)執(zhí)行以下命令時,會執(zhí)行所有的TestCase的所有Test。測試的對象是在Target Package中指定的包中的代碼:

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

  如果你想運(yùn)行一個TestSuite,首先繼承android.jar的junit.framework.TestSuite類,實現(xiàn)一個 TestSuite(比如叫com.android.foo.MyTestSuite),然后執(zhí)行以下命令執(zhí)行此TestSuite

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

  其中的-e表示額外的參數(shù),語法為-e [arg1] [value1] [arg2] [value2] …這里用到了class參數(shù)。

  如果僅僅想運(yùn)行一個TestCase(比如叫com.android.foo.MyTestCase),則用以下命令:

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

  如果僅僅想運(yùn)行一個Test(比如是上面MyTestCase的testFoo方法),很類似的,這樣寫:

  adb shell am instrument -e class com.android.foo.MyTestCase#testFoo -w com.android.foo/android.test.InstrumentationTestRunner

  然后,所有的測試結(jié)果會輸出到控制臺,并會做一系列統(tǒng)計,如標(biāo)記為E的是Error,標(biāo)記為F的是Failure,Success的測試則會標(biāo)記為一 個點。這和JUnit的語義一致。如果希望斷點調(diào)試你的測試,只需要直接在代碼上加上斷點,然后將運(yùn)行命令參數(shù)的-e后邊附加上debug true后運(yùn)行即可。更加詳細(xì)的內(nèi)容可以看InstrumentationTestRunner的Javadoc。我希望Android能盡快有正式的文檔來介紹這個內(nèi)容。

  如何在Android的單元測試中做標(biāo)記?

  在 android.test.annotation包里定義了幾個annotation,包括 @LargeTest,@MediumTest,@SmallTest,@Smoke,和@Suppress。你可以根據(jù)自己的需要用這些 annotation來對自己的測試分類。在執(zhí)行單元測試命令時,可以在-e參數(shù)后設(shè)置“size large”/ “size medium”/ “size small”來執(zhí)行具有相應(yīng)標(biāo)記的測試。特別的@Supperss可以取消被標(biāo)記的Test的執(zhí)行。

  完整的操作過程

  總結(jié)以上所有的內(nèi)容,編寫并運(yùn)行完整的測試需要以下的步驟:

  以上步驟中,在 Android自帶的例子中,我發(fā)現(xiàn)它有兩個manifest.xml。也是說在步驟3中源代碼和測試代碼分別生成了兩個不同的包。然后步驟4利用 adb install命令安裝到了虛擬機(jī)上。由于我沒有找到Eclipse ADT有辦法可以為一個只有Instrumentation,沒有Activity的Application打包并安裝,于是采用了略微不同的辦法完成了這個工作。下文中將一一詳細(xì)介紹整個過程。

wordend 相關(guān)閱讀:

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

  1、編寫程序

  我新建了一個項目TestApp,參數(shù)為:

  Package Name: com.android.testapp

  Activity Name: MainActivity

  Application Name: TestApp

  以下是MainActivity的源代碼:

  packagecom.android.testapp;

  importandroid.app.Activity;

  importandroid.os.Bundle;

  publicclassMainActivityextendsActivity {

  

  @Override

  publicvoidonCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  }

  publicintsum(inta,intb) {

  returna + b;

  }

  publicintsubstract(inta,intb) {

  returnb - a;

  }

  }

  其中,我故意將減法的a – b寫成了b – a。

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