如果你需要實(shí)現(xiàn)自動(dòng)測(cè)試,Android 的 monkeyrunner 工具可以幫助你實(shí)現(xiàn)自動(dòng)測(cè)試,它提供了一組 API 可以用來(lái)控制 Android 設(shè)備或模擬器,使用 monkeyrunner,你可以編寫(xiě) Python 程序來(lái)安裝 Android 應(yīng)用或是測(cè)試包,運(yùn)行應(yīng)用或測(cè)試,發(fā)送按鍵消息,并可以截屏,然后保存在計(jì)算機(jī)中。monkeyrunner 主要目的是用來(lái)在應(yīng)用程序或框架層次來(lái)測(cè)試應(yīng)用程序或運(yùn)行單元測(cè)試包,但你也可以用作其它目的。
monkeyrunner 工具包不同于 UI/Application Exerciser Monkey(也稱為 Money),money 通過(guò) adb shell 來(lái)運(yùn)行,可以模擬“猴子”隨機(jī)按鍵或是發(fā)送系統(tǒng)消息給指定的應(yīng)用來(lái)實(shí)現(xiàn) Stress 測(cè)試。
monkeyrunner API 主要通過(guò)下面三個(gè)包:
下面為一個(gè) Python 寫(xiě)的 monkeyrunner 應(yīng)用, 因?yàn)樯婕暗?Python 語(yǔ)言,這里不詳細(xì)說(shuō)明了
# 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')
詳細(xì)的 API 說(shuō)明請(qǐng)參考 Android 文檔 ,如果你需要實(shí)現(xiàn)自動(dòng)測(cè)試,編寫(xiě)測(cè)試代碼,可以使用 Python 通過(guò) monkeyrunner API 來(lái)實(shí)現(xiàn)。