如果假設(shè)com.android.foo是你的測(cè)試代碼的包的根。當(dāng)執(zhí)行以下命令時(shí),會(huì)執(zhí)行所有的TestCase的所有Test。測(cè)試的對(duì)象是在Target Package中指定的包中的代碼:
adb shell am instrument -w com.android.foo/android.test.InstrumentationTestRunner
如果你想運(yùn)行一個(gè)TestSuite,首先繼承android.jar的junit.framework.TestSuite類,實(shí)現(xiàn)一個(gè) 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)行一個(gè)TestCase(比如叫com.android.foo.MyTestCase),則用以下命令:
adb shell am instrument -e class com.android.foo.MyTestCase -w com.android.foo/android.test.InstrumentationTestRunner
如果僅僅想運(yùn)行一個(gè)Test(比如是上面MyTestCase的testFoo方法),很類似的,這樣寫:
adb shell am instrument -e class com.android.foo.MyTestCase#testFoo -w com.android.foo/android.test.InstrumentationTestRunner
然后,所有的測(cè)試結(jié)果會(huì)輸出到控制臺(tái),并會(huì)做一系列統(tǒng)計(jì),如標(biāo)記為E的是Error,標(biāo)記為F的是Failure,Success的測(cè)試則會(huì)標(biāo)記為一 個(gè)點(diǎn)。這和JUnit的語義一致。如果希望斷點(diǎn)調(diào)試你的測(cè)試,只需要直接在代碼上加上斷點(diǎn),然后將運(yùn)行命令參數(shù)的-e后邊附加上debug true后運(yùn)行即可。更加詳細(xì)的內(nèi)容可以看InstrumentationTestRunner的Javadoc。我希望Android能盡快有正式的文檔來介紹這個(gè)內(nèi)容。
如何在Android的單元測(cè)試中做標(biāo)記?
在 android.test.annotation包里定義了幾個(gè)annotation,包括 @LargeTest,@MediumTest,@SmallTest,@Smoke,和@Suppress。你可以根據(jù)自己的需要用這些 annotation來對(duì)自己的測(cè)試分類。在執(zhí)行單元測(cè)試命令時(shí),可以在-e參數(shù)后設(shè)置“size large”/ “size medium”/ “size small”來執(zhí)行具有相應(yīng)標(biāo)記的測(cè)試。特別的@Supperss可以取消被標(biāo)記的Test的執(zhí)行。
完整的操作過程
總結(jié)以上所有的內(nèi)容,編寫并運(yùn)行完整的測(cè)試需要以下的步驟:
以上步驟中,在 Android自帶的例子中,我發(fā)現(xiàn)它有兩個(gè)manifest.xml。也是說在步驟3中源代碼和測(cè)試代碼分別生成了兩個(gè)不同的包。然后步驟4利用 adb install命令安裝到了虛擬機(jī)上。由于我沒有找到Eclipse ADT有辦法可以為一個(gè)只有Instrumentation,沒有Activity的Application打包并安裝,于是采用了略微不同的辦法完成了這個(gè)工作。下文中將一一詳細(xì)介紹整個(gè)過程。
wordend 相關(guān)閱讀:
MOTODEV初體驗(yàn),高效Android開發(fā)工具
詳解如何實(shí)現(xiàn)一個(gè)基本的Android用戶界面
Android應(yīng)用開發(fā)實(shí)戰(zhàn):GPS與加速度傳感器
1、編寫程序
我新建了一個(gè)項(xiàng)目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。