读书人

MonkeyRunner的应用

发布时间: 2013-02-03 12:33:31 作者: rapoo

MonkeyRunner的使用
要使用MonkeyRunner,就要学习使用Python,哎

先抄一段官方doc里的代码
作用是启动一个程序(应该是启动程序默认的Activity),然后按MENU键,并截屏

# Imports the monkeyrunner modules used by this programfrom com.android.monkeyrunner import MonkeyRunner as mrfrom com.android.monkeyrunner import MonkeyDevice as md# Connects to the current device, returning a MonkeyDevice objectdevice = mr.waitForConnection()# sets a variable with the package's internal namepackage = 'com.example.android.myapplication'# sets a variable with the name of an Activity in the packageactivity = 'com.example.android.myapplication.MainActivity'# sets the name of the component to startrunComponent = package + '/' + activity# Runs the componentdevice.startActivity(component=runComponent)# Presses the Menu buttondevice.press('KEYCODE_MENU', MonkeyDevice.DOWN_AND_UP)# Takes a screenshotresult = device.takeSnapshot()# default folder name to save snapshotsnapshot = 'E:\\tmp\\'# Writes the screenshot to a fileresult.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 sysimport os# this must be imported before MonkeyRunner and MonkeyDevice,# otherwise the import failsANDROID_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.3from com.android.chimpchat.hierarchyviewer import HierarchyViewerfrom com.android.hierarchyviewerlib.device import ViewNodehv = device.getHierarchyViewer() vn = hv.findViewById('id/icon_menu')

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

读书人网 >移动开发

热点推荐