欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

MonkeyRunner的使用

程序员文章站 2022-05-11 12:18:13
...
要使用MonkeyRunner,就要学习使用Python,哎

先抄一段官方doc里的代码
作用是启动一个程序(应该是启动程序默认的Activity),然后按MENU键,并截屏
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner as mr
from com.android.monkeyrunner import MonkeyDevice as md

# Connects to the current device, returning a MonkeyDevice object
device = mr.waitForConnection()

# 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()

# default folder name to save snapshot
snapshot = 'E:\\tmp\\'	

# Writes the screenshot to a file
result.writeToFile(snapshot + 'shot1.png','png')

当然这个离我们的自动化测试还很遥远

如果要检验文本,就需要获得View,而希望获得View,就需要设备支持启动View Service,如果要启动View Service,设备就必须是开发机(root后还不一定是开发机),或者模拟器。

要获得View,可以使用第三方的插件ViewClient,当然也可以用MonkeyRunner自带的HierarchyViewer和ViewNode(仅在2.3.3以后支持)

使用ViewClient

如果要使用ViewClient,就去GitHub下载一个https://github.com/dtmilano/AndroidViewClient

然后配置一下环境,增加ANDROID_VIEW_CLIENT_HOME(其实不配置也OK)就可以使用了
import sys
import os

# this must be imported before MonkeyRunner and MonkeyDevice,
# otherwise the import fails
ANDROID_VIEW_CLIENT_HOME = os.environ['ANDROID_VIEW_CLIENT_HOME']
sys.path.append(ANDROID_VIEW_CLIENT_HOME + '/src')

from com.dtmilano.android.viewclient import ViewClient


需要注意,ViewClient获取adb路径的判断,对Windows支持得不太好,有些地方的判断需要自己修改一下才能运行

2.0版,对adb的可执行性的check,没有考虑平台的差异性,统一用os.access(xxx, os.X_OK)
2.3版,增加了isWindows的判断,但是获取exeFile的时候又出现同样错误

使用HierarchyViewer和ViewNode

# Support from 2.3.3
from com.android.chimpchat.hierarchyviewer import HierarchyViewer
from com.android.hierarchyviewerlib.device import ViewNode

hv = device.getHierarchyViewer() 
vn = hv.findViewById('id/icon_menu')

调查到此为止,果断回归NativeDriver