命令行demo如下:
adb shell am instrument -e class com.autonavi.MinimapAutomationTool#testLayerCancelButton -w com.autonavi/android.test.InstrumentationTestRunner
命令解析:
start an Instrumentation: am instrument [flags] <COMPONENT>
-r: print raw results (otherwise decode REPORT_KEY_STREAMRESULT)
-e <NAME> <VALUE>: set argument <NAME> to <VALUE>
-p <FILE>: write profiling data to <FILE>
-w: wait for instrumentation to finish before returning
-e后面加參數 class就可以指定一個測試類,里面包含了若干個測試方法。
按照android幫助文檔里面的名稱,testsuite包含了若干個testcase,一個testcase其實就是一個測試類。
比如:Run the instrumentation using "adb shell am instrument -w", with the argument '-e class' set to run an individual .
如果想指定只執行某一個測試方法,就需要用#testxxx.第一個命令行demo.
有時候也可以用$符號,但是有什么區別,沒有去研究。
以下是一些copy來的文檔,個人覺得比較有用:
在介紹具體的命令之前,我們先理解一下單元測試的層次。一組單元測試可以被組織成若干個TestSuite。每個TestSuite包含若干 TestCase(某個繼承android.jar的junit.framework.TestCase的類)。每個TestCase又包含若干個 Test(具體的test方法)。
如果假設com.android.foo是你的測試代碼的包的根。當執行以下命令時,會執行所有的TestCase的所有Test。測試的對象就是在Target Package中指定的包中的代碼:
adb shell am instrument -w com.android.foo/android.test.InstrumentationTestRunner
如果你想運行一個TestSuite,首先繼承android.jar的junit.framework.TestSuite類,實現一個 TestSuite(比如叫com.android.foo.MyTestSuite),然后執行以下命令執行此TestSuite
adb shell am instrument -e class com.android.foo.MyTestSuite -w com.android.foo/android.test.InstrumentationTestRunner
其中的-e表示額外的參數,語法為-e [arg1] [value1] [arg2] [value2] …這里用到了class參數。
如果僅僅想運行一個TestCase(比如叫com.android.foo.MyTestCase),則用以下命令:
adb shell am instrument -e class com.android.foo.MyTestCase -w com.android.foo/android.test.InstrumentationTestRunner
如果僅僅想運行一個Test(比如就是上面MyTestCase的testFoo方法),很類似的,就這樣寫:
adb shell am instrument -e class com.android.foo.MyTestCase#testFoo -w com.android.foo/android.test.InstrumentationTestRunner
然后,所有的測試結果會輸出到控制台,並會做一系列統計,如標記為E的是Error,標記為F的是Failure,Success的測試則會標記為一個點。這和JUnit的語義一致。如果希望斷點調試你的測試,只需要直接在代碼上加上斷點,然后將運行命令參數的-e后邊附加上debug true后運行即可。更加詳細的內容可以看InstrumentationTestRunner的Javadoc。我希望Android能盡快有正式的文檔來介紹這個內容。
如何在Android的單元測試中做標記?
在 android.test.annotation包里定義了幾個annotation,包括 @LargeTest,@MediumTest,@SmallTest,@Smoke,和@Suppress。你可以根據自己的需要用這些 annotation來對自己的測試分類。在執行單元測試命令時,可以在-e參數后設置“size large”/ “size medium”/ “size small”來執行具有相應標記的測試。特別的@Supperss可以取消被標記的Test的執行。
完整的操作過程
總結以上所有的內容,編寫並運行完整的測試需要以下的步驟:
以上步驟中,在 Android自帶的例子中,我發現它有兩個manifest.xml。也就是說在步驟3中源代碼和測試代碼分別生成了兩個不同的包。然后步驟4利用 adb install命令安裝到了虛擬機上。由於我沒有找到Eclipse ADT有辦法可以為一個只有Instrumentation,沒有Activity的Application打包並安裝,於是采用了略微不同的辦法完成了這個工作。下文中將一一詳細介紹整個過程。
轉自:http://hi.baidu.com/maguowei/item/8cc4d933755a41149cc65ea2