MonkeyRunner与它的三大模块

前面的内容请参见Android应用自动化测试-提纲。

上篇说到MonkeyRunner中有三个主要的模块MonkeyRunner、MonkeyDevice、MonkeyImage。本篇就总结下这三个模块的具体用法:

MonkeyRunner模块的主要方法

返回类型 方法 作用
void alert (string message, string title, string okTitle) 显示一个弹出警告对话框
integer choice (string message, iterable choices, string title) 显示一个带下拉选择的对话框
void help (string format) 根据给定的format格式显示MonkeyRunner工具的API说明
string input (string message, string initialValue, string title, string okTitle, string cancelTitle) 显示说明输入对话框
void sleep (float seconds) 终止程序运行指定时间
MonkeyDevice waitForConnection (float timeout, string deviceId) 建立MonkeyRunner和android设备之间的连接

这里最常用的是waitforconnection方法,返回一个MonkeyDevice对象,用于建立和设备的连接。

另外help这个方法可以生成一个MonkeyRunner的帮助文档,但大家在执行的时候可能会出错。


这应该是MonkeyRunner工具的一个bug. 因为这个方法需要调用的资源文件没有包含在SDK中,所以要使用这个方法,需要把MonkeyRunner源码中的resource目录拷贝到MonkeyRunner工具所在SDK目录的lib文件夹下,再执行这个方法就可以了

MonkeyRunner与它的三大模块_第1张图片

其他的几个方法主要是用于执行交互的对话框操作,比如alert对话框

MonkeyRunner与它的三大模块_第2张图片

MonkeyDevice模块的主要方法

返回类型 方法 作用
void broadcastIntent (string uri, string action, string data, string mimetype, iterable categories dictionary extras, component component, iterable flags) 模拟application对象向设备广播 Intent.
void drag (tuple start, tuple end, float duration, integer steps) 触发拖动操作
object getProperty (string key) 获取给定系统环境变量值,可用的变量清单参见detailed description
object getSystemProperty (string key) 开发者调试方法,用法和adb shell getprop .相同
void installPackage (string path) 向设备安装应用,如果应用已存在,则替换
dictionary instrument (string className, dictionary args) 运行指定的 instrumentation组件,组件必须已经保存在设备上了
void press (string name, dictionary type) 根据给定的keycode执行press操作
void reboot (string into) 重启设备
void removePackage (string package) 删除应用,包括缓存和数据
object shell (string cmd) 执行一个adb shell 命令
void startActivity (string uri, string action, string data, string mimetype, iterable categories dictionary extras, component component, flags) 通过发送一个Intent来启动指定Activity
MonkeyImage takeSnapshot() 获取整个屏幕界面并返回一个MonkeyImage对象
void touch (integer x, integer y, integer type) 发送一个点击指定坐标的touch事件
void type (string message) 发送一组字符输入事件,和使用press方法来输入字符并发送按键事件DOWN_AND_UP效果相同
void wake () 唤醒设备屏幕

这个模块下主要是设备控制的相关操作,也是MonkeyRunner中实际承担自动化操作的主要模块。如启动一个计算器应用


MonkeyRunner与它的三大模块_第3张图片

MonkeyImage模块的主要方法

返回类型 方法 作用
string convertToBytes (string format) 将图像转换为二进制字节码内容并以string返回
tuple getRawPixel (integer x, integer y) 给出指定坐标处像素点的 (a,r,g,b)像素值
integer getRawPixelInt (integer x, integer y) 给出指定像素点处的整形像素值
MonkeyImage getSubImage (tuple rect) 根据给定区域生成一个新的MonkeyImage对象
boolean sameAs (MonkeyImage other, float percent) 比较对象相似度
void writeToFile (string path, string format) 将MonkeyImage对象保存到指定格式的图像文件中

这个模块则是图像保存和比对的功能。这里需要说明的是,MonkeyRunner的sameAs方法,调用的是android源码中的chimpchat类的图像比较方法,精度不高,建议使用的时候尽量先获取subImage来缩小比较范围来提高结果准确性。


关于android自动化测试的更多实战操作演示参见慕课网实战课程 Android自动化测试实战 工具 框架 脚本

欢迎保留作者信息和出处进行转载,欢迎关注微信公众号:秋草说测试。 原创测试干货资源池


你可能感兴趣的:(MonkeyRunner与它的三大模块)