Instrumentation

一般在開發Android程序的時候,需要寫一個manifest文件在啓動程序的時候就會先啓動一個Application,然後在此Application運行過程中根據情況加載相應的Activity,而Activity是需要一個界面的。但是Instrumentation並不是這樣的。你可以將Instrumentation理解爲一種沒有圖形界面的,具有啓動能力的,用於監控其他類(用TargetPackage聲明)的工具類。任何想成爲Instrumentation的類必須繼承android.app.Instrumentation。

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

在介紹具體的命令之前,我們先理解一下單元測試的層次。

一組單元測試可以被組織成若干個TestSuite。每個TestSuite包含若干TestCase(某個繼承android.jar的junit.framework.TestCase的類)。每個TestCase又包含若干個Test(具體的test方法)。

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

adb shell am instrument -wcom.android.foo/android.test.InstrumentationTestRunner

(2)如果你想運行一個TestSuite,首先繼承android.jar的junit.framework.TestSuite類,實現一個TestSuite(比如叫com.android.foo.MyTestSuite),然後執行以下命令執行此TestSuite

adb shell am instrument -eclass com.android.foo.MyTestSuite -wcom.android.foo/android.test.InstrumentationTestRunner

其中的-e表示額外的參數,語法爲-e [arg1] [value1] [arg2] [value2] …這裏用到了class參數。

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

adb shell am instrument -eclass com.android.foo.MyTestCase -wcom.android.foo/android.test.InstrumentationTestRunner

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

adb shell am instrument -eclass com.android.foo.MyTestCase#testFoo -wcom.android.foo/android.test.InstrumentationTestRunner

然後,所有的測試結果會輸出到控制檯,並會做一系列統計,如標記爲E的是Error,標記爲F的是Failure,Success的測試則會標記爲一個點。這和JUnit的語義一致。如果希望斷點調試你的測試,只需要直接在代碼上加上斷點,然後將運行命令參數的-e後邊附加上debug true後運行即可。更加詳細的內容可以看InstrumentationTestRunner的Java.doc。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章