没有写blog习惯,整理了下去年的学习记录,贴出来希望能给他人一些启发;
MonkeyRunner简介
Monkeyrunner是用python编码实现的测试,是Monkey的升级版从随机事件流变成有逻辑的模拟用户按键、触屏、滑动操作,控制事件、随时截图。最主要是通过运行程序,在程序中提供按键或触摸事件的输入数值然后截屏,通过截屏对比是否是正常的运行。
MonkeyRunner API主要包括三个模块:
- Monkeyrunner:这个类提供了用于连接设备或者模拟器的方法。
- MonkeyDevice:这个类为安装、卸载APK,启动activity发送按键和触摸事件运行测试包的方法。
- MonkeyImage:这个类提供了截图、对比保存的方法。
MonkeyRunner特点:
编写语言:Python
运行环境:Python 环境,adb链接PC运行
测试对象:UI测试
测试限制:主要使用坐标,逻辑判断能力差
MonkeyRunner使用方法:
- 引入MonkeyRunner中所要用的模块:
from com.android.monkeyrunner
import MonkeyRunner,MonkeyDevice,MonkeyImage - 与设备链接(没有报错即链接成功)
device=MonkeyRunner.waitForConnection()
- 卸载、安装要测试的APK
device.removePackage('android-3.7.3.apk')
device.installPackage('d:/android-3.7.3.apk') - 启动任意Activity
componentName = 'com.itangyuan/.module.portlet.FlashActivity'
device.startActivity(component=componentName) - 打开菜单
device.press('KEYCODE_MENU','DOWN_AND_UP')
- 点击某一坐标点
device.touch(35,75,'DOWN_AND_UP')
- 运行截图
pic=device.takeSnapshot()
- 正确结果截图
resultTrue=MonkeyRunner.loadImageFromFile(r"d:\login.png")
- 使用.sameAs()对比两张图片,并输出对比结果True或False
print (pic.sameAs(resultTrue,0.9))
更多API参考
MonkeyRunner脚本示例:
Demo 1:
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice,MonkeyImage
# 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 star