如果你需要實現自動化的測試,Android的monkeyrunner 工具可以協助你實現自動化的測試,它提供了一組API可以用來控制Android裝置或模擬器,使用monkeyrunner,你可以編寫Python 程式來安裝Android應用或是測試包,運行應用或測試,發送按鍵訊息,並可以截屏,然後儲存在電腦中。monkeyrunner 主要目的是用來在應用程式或架構層次來測試應用程式或運行單元測試包,但你也可以用作其它目的。
monkeyrunner 工具包不同於UI/Application Exerciser Monkey(也稱為Money),money 通過adb shell 來運行,可以類比“猴子”隨機按鍵或是發送系統訊息給指定的應用來實現Stress 測試。
monkeyrunner API 主要通過下面三個包:
MonkeyRunner: 主要提供了monkeyrunner 應用的輔助方法以及,用來連結裝置或是模擬器的方法,並提供UI支援等。
MonkeyDevice: 代表一個裝置或是模擬器,提供安裝,卸載應用的方法,啟動一個Activity,發送按鍵或是Touch 事件等。
MonkeyImage: 代表一個截屏映像,可以截取不同格式的映像,比較兩個MonkeyImage映像,儲存映像等。
下面為一個 Python 寫的monkeyrunner 應用, 因為涉及到Python 語言,這裡不詳細說明了
# Imports the monkeyrunner modules used by this program from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice # Connects to the current device, returning a MonkeyDevice object device = MonkeyRunner.waitForConnection() # Installs the Android package. Notice that this method returns a boolean, # so you can test to see if the installation worked. device.installPackage('myproject/bin/MyApplication.apk') # sets a variable with the package's internal name package = 'com.example.android.myapplication' # sets a variable with the name of an Activity in the package activity = 'com.example.android.myapplication.MainActivity' # sets the name of the component to start runComponent = package + '/' + activity # Runs the component device.startActivity(component=runComponent) # Presses the Menu button device.press('KEYCODE_MENU','DOWN_AND_UP') # Takes a screenshot result = device.takeSnapshot() # Writes the screenshot to a file result.writeToFile('myproject/shot1.png','png')
詳細的API說明請參考Android文檔(http://developer.android.com/guide/developing/tools/monkeyrunner_concepts.html) ,如果你需要實現自動化的測試,編寫測試代碼,可以使用Python通過monkeyrunner API來實現。
查看全套教程:http://www.bianceng.cn/OS/extra/201301/35252.htm