前面的內容請參見Android應用自動化測試-提綱。
這篇開始我們來看從Android早期版本的SDK中就自帶的一個黑盒自動化測試工具-MonkeyRunner。雖然名字中也有Monkey,但是MonkeyRunner和Monkey基本沒有太大關系。Monkey是運行在Adb shell中的,實際執行在設備本身。而MonkeyRunner則是通過PC端,由Android的API接口來控制設備,進行自動化測試的執行,其主要邏輯是在PC端完成的。
MonkeyRunner支持用Jython(Python腳本的java實現,語法和Python一致)腳本完成自動化測試腳本,可以實現Monkey工具無法提供的邏輯控制、校驗等功能。
在Google的官網上有對MonkeyRunner的介紹,并提供了一個腳本示例,實現了應用的安裝、啟動并對啟動后的界面完成截屏操作。
# 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', MonkeyDevice.DOWN_AND_UP)
# Takes a screenshot
result = device.takeSnapshot()
# Writes the screenshot to a file
result.writeToFile('myproject/shot1.png','png')
MonkeyRunner主要由三大模塊組成:MonkeyRunner、MonkeyDevice、MonkeyImage
- MonkeyRunner -- 包含一些通用的靜態方法
- MonkeyDevice -- MonkeyRunner可以控制的設備或模擬器的實體類,可以完成發送UI事件、獲取設備信息、安裝卸載運行應用等工作
- MonkeyImage -- 圖像處理類,可以獲取當前設備屏幕并完成基本校驗。
MonkeyRunner工具位于Android SDK的tools目錄下,通過運行monkeyrunner.bat(Linux下monkeyrunner.sh)即可啟動MonkeyRunner的交互界面:
>monkeyrunner
Jython 2.5.3 (2.5:c56500f08d34+, Aug 13 2012, 14:54:35)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_91
>>>