安卓app测试之Monkeyrunner

一、MonkeyRunner简介

MonkeyRunner提供了系列的API ,MonkeyRunner可以完成模拟事件及截图操作 ,分为以下三类:

MonkeyRunner:用来连接设备或模拟器的

MonkeyDevice:提供安装、卸载应用,发送模拟事件

MonkeyImage:完成图像保存及对比的操作

  • 多设备控制 
  • 功能测试
  • 回归测试

二、MonkeyRunnerAPI

1、alert ——警告框

MonkeyRunner.alert(string message, string title, string okTitle)

  • message: 弹出对话框内容
  • title: 对话框的标题栏显示内容,默认值为"Alert"
  • okTitle : 对话框的按钮,默认值为"OK

2、waitForConnection —— 等待设备连接,多个设备,需要指明哪个设备 

MonkeyRunner.waitForConnection(float timeout, string deviceId) 

  • timeout: 等待超时时间,默认值为永久等待. 
  • deviceId: 通过设备ID去设别手机或模拟器.如果只有一台手机的时候,不需要输入.

三、MonkeyDeviceAPI

1、drag ——拖动

device.drag(tuple start, tuple end, float duration, integer steps) 

  • start:起始点位置【(1,2)】
  • end:终点位置 【 (3,4)】
  • duration:手势持续的时间
  • steps:插值点的步数,默认10

2、press —— 按键

device.press(string keycode,dictionary type) 

  • type:DOWN、UP、DOWN_AND_UP

3、startActivity ——启动应用

device.startActivity(package+'/'+activity)

4、touch —— 点击

device.touch(int x,int y,type)

  • type:DOWN、UP、DOWN_AND_UP

5、type —— 输入 

device.type(string message)

6、takeSnapshot——截屏 

device.takeSnapshot()

四、MonkeyImageAPI

1、sameAs —— 图像对比 

picture.sameAs(MonkeyImage other,float percent) 

  • percent:对比相似度

2、writetoFile ——保存图像文件

picture.writeToFile(string path,string format)

  • string path,存储全路径,包括文件扩展名。 
  • string format,存储格式

五、MonkeyRunner实战 

刚才那个例子,打开手机浏览器,输入百度,在百度搜索框中输入Helloween,点击搜索

步骤如上,新建一个script文件,脚本写入下:

 1 from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
 2 device = MonkeyRunner.waitForConnection(5,"192.168.243.101:5555")
 3 device.startActivity("com.android.browser/.BrowserActivity")
 4 MonkeyRunner.sleep(5)
 5 device.touch(200,100,'DOWN_AND_UP')
 6 MonkeyRunner.sleep(1)
 7 device.press('KEYCODE_FORWARD_DEL','DOWN_AND_UP')
 8 device.type('www.baidu.com')
 9 device.press('KEYCODE_ENTER','DOWN_AND_UP')
10 MonkeyRunner.sleep(10)
11 device.touch(300,400,'DOWN_AND_UP')
12 MonkeyRunner.sleep(1)
13 device.type('Helloween')
14 MonkeyRunner.sleep(3)
15 device.press('KEYCODE_ENTER','DOWN_AND_UP')
16 MonkeyRunner.sleep(10)
17 image=device.takeSnapshot()
18 image.writeToFile('C:\Users\wuzm\Desktop\test_1234.png','png')
19 MonkeyRunner.sleep(3)

六、Monkey和MonkeyRunner的区别 

Monkey:在adb shell中,生成用户或系统的伪随机事件

MonkeyRunner:通过API定义特定命令和事件控制设备

原文地址:https://www.cnblogs.com/wuzm/p/10967803.html