monkeyrunner.bat运行python脚本/命令行

monkeyrunner.bat运行python脚本/命令行

今天折腾了一把monkeyrunner,分别使用命令行和python连接monkeyrunner:

命令行连接monkeyrunner测试:

1.打开android的模拟器,或将android手机连接到电脑

2.运行monkeyrunner.bat,接下来就可以在打开的命令行窗口中输入命令。

导入monkeyrunner使用的模块直接在命令行中输入:
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

将模拟器和MonkeyRunner绑定,绑定后在monkeyrunner的操作等同于在模拟器的操作
device = MonkeyRunner.waitForConnection()

安装一个apk应用包,以SDK自带Apidemos.apk包为例,输入如下命令,成功会返回true
device.installPackage(“./Apidemos.apk”)

注:‘./ApiDemos.apk’表示当前路径下的ApiDemos.apk,其他路径则填写完整路径如“D:/路径目录/ApiDemos.apk”

接下来,我们就可以启动其中的任意activity了,只要传入package和activity名称即可。模拟打开ApiDemos的主页示例如下:
device.startActivity(component = “com.example.android.apis/com.example.android.apis.ApiDemos”)

我们还可以给模拟器发送更多的操作,如模拟任何按键时间和滚动等,并且可以截图。

monkeyrunner.bat运行python脚本方法如下:

自动化测试肯定不能这么一行行的敲命令,monkeyrunner运行python脚本方法网上有很多介绍,但windows平台并且只有monkeyrunner.bat的运行方法只找到了一种

将一些内容保存如monkeyrunnerTest.py:

# 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(‘./ApiDemos.apk’)

# Runs the component
device.startActivity(component=’com.example.android.apis/.ApiDemos’)

# Presses the Menu button
device.press(‘KEYCODE_MENU’,’DOWN_AND_UP’)
device.press(‘KEYCODE_DPAD_DOWN’,’DOWN_AND_UP’)
device.press(‘KEYCODE_DPAD_UP’,’DOWN_AND_UP’)

# Takes a screenshot
result = device.takeSnapshot()
# Writes the screenshot to a file
result.writeToFile(‘./shot.png’,’png’)

脚本安装并打开指定应用,然后依次模拟按下“菜单/下/上”键,最后截图并保存。

然后我们打开cmd命令行窗口,命令行中运行脚本即可:
monkeyrunner.bat monkeyrunnerTest.py

可根据根据路径运行,上例两个文件在同一目录,并且命令行切换到了该目录。

6san.com

发表评论