初窥门径-MonkeyRunner

前面的内容请参见Android应用自动化测试-提纲
这篇开始我们来看从Android早期版本的SDK中就自带的一个黑盒自动化测试工具-MonkeyRunner。虽然名字中也有Monkey,但是MonkeyRunner和Monkey基本没有太大关系。Monkey是运行在Adb shell中的,实际执行在设备本身。而MonkeyRunner则是通过PC端,由Android的API接口来控制设备,进行自动化测试的执行,其主要逻辑是在PC端完成的。
MonkeyRunner支持用Jython(Python脚本的java实现,语法和Python一致)脚本完成自动化测试脚本,可以实现Monkey工具无法提供的逻辑控制、校验等功能。

在Google的官网上有对MonkeyRunner的介绍,并提供了一个脚本示例,实现了应用的安装、启动并对启动后的界面完成截屏操作。

# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice

# 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('myproject/bin/MyApplication.apk')

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

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

MonkeyRunner主要由三大模块组成:MonkeyRunner、MonkeyDevice、MonkeyImage

  • MonkeyRunner -- 包含一些通用的静态方法
  • MonkeyDevice -- MonkeyRunner可以控制的设备或模拟器的实体类,可以完成发送UI事件、获取设备信息、安装卸载运行应用等工作
  • MonkeyImage -- 图像处理类,可以获取当前设备屏幕并完成基本校验。

MonkeyRunner工具位于Android SDK的tools目录下,通过运行monkeyrunner.bat(Linux下monkeyrunner.sh)即可启动MonkeyRunner的交互界面:

>monkeyrunner
Jython 2.5.3 (2.5:c56500f08d34+, Aug 13 2012, 14:54:35)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0_91
>>>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容