Monkey是Android开发中常用的一个命令行工具,主要用于进行压力测试,通过模拟用户随机操作来检测应用程序的稳定性、响应性和崩溃情况,以下是Monkey常用命令的详细说明,包括基本用法、参数配置及实际应用场景。

Monkey命令的基本语法结构为:adb shell monkey [options] <event-count>,其中options用于控制测试行为,event-count表示发送事件的总数量,最简单的命令是adb shell monkey 100,表示发送100个随机事件,在实际测试中,通常会结合多种参数来定制测试场景。
常用参数分类说明
-
基本参数
-p <package-name>:指定测试的应用包名,可多次使用以测试多个应用。adb shell monkey -p com.example.app1 -p com.example.app2 100。-c <main-category>:指定Intent类别,如android.intent.category.LAUNCHER。adb shell monkey -c android.intent.category.LAUNCHER 100。--throttle <milliseconds>:设置事件之间的间隔时间(毫秒),默认为0。--throttle 500表示每个事件间隔500毫秒。--pct-touch <percent>:触摸事件百分比(默认为50%)。--pct-touch 30将触摸事件比例降至30%。
-
事件类型参数
Monkey支持多种事件类型,可通过参数调整比例:--pct-motion <percent>:滑动事件百分比(默认为25%)。--pct-trackball <percent>:轨迹球事件百分比(默认为0%)。--pct-nav <percent>:导航事件(如返回键、菜单键)百分比(默认为25%)。--pct-majornav <percent>:主要导航事件百分比(默认为35%)。--pct-syskeys <percent>:系统按键事件百分比(默认为0%)。--ppt-appswitch <percent>:应用切换事件百分比(默认为10%)。--pct-anyevent <percent>:其他事件百分比(默认为0%)。
若需模拟更多触摸和滑动事件,可设置:
adb shell monkey --pct-touch 60 --pct-motion 30 1000。
(图片来源网络,侵删) -
调试与日志参数
-v:输出详细日志,可叠加使用(如-v -v -v)显示更详细的信息。--ignore-crashes:忽略崩溃,继续执行测试。--ignore-timeouts:忽略超时错误。--ignore-security-exceptions:忽略安全异常。--monitor-native-crashes:监控本地代码崩溃。--hprof:测试结束后生成堆转储文件(用于内存分析)。
adb shell monkey -v --ignore-crashes 500。 -
种子值(Seed)参数
种子值用于复现测试场景,相同种子值会生成相同的事件序列。adb shell monkey --seed 1234 100。 -
限制与过滤参数
(图片来源网络,侵删)--ignore-crashes:忽略应用崩溃。--wait-dbg:等待调试器连接后开始测试。--dbg-no-events:启动应用后不发送事件。
实际应用示例
-
基础压力测试
测试单个应用,发送1000个随机事件:
adb shell monkey -p com.example.app 1000。 -
多应用测试
同时测试两个应用,并设置事件间隔:
adb shell monkey -p com.example.app1 -p com.example.app2 --throttle 300 2000。 -
自定义事件比例
模拟更多触摸和滑动事件:
adb shell monkey --pct-touch 70 --pct-motion 20 --pct-nav 10 500。 -
带日志的崩溃测试
忽略崩溃并输出详细日志:
adb shell monkey -v -v --ignore-crashes 1000。
参数速查表
| 参数类别 | 参数示例 | 说明 |
|---|---|---|
| 基本参数 | -p com.example.app |
指定测试包名 |
--throttle 500 |
事件间隔500毫秒 | |
| 事件类型 | --pct-touch 60 |
触摸事件占比60% |
--pct-motion 30 |
滑动事件占比30% | |
| 调试与日志 | -v |
输出详细日志 |
--ignore-crashes |
忽略崩溃 | |
| 种子值 | --seed 1234 |
复现测试场景 |
| 限制与过滤 | --wait-dbg |
等待调试器连接 |
相关问答FAQs
Q1: Monkey测试时如何捕获应用崩溃信息?
A: 可以通过adb logcat实时查看日志,或使用adb shell monkey -v中的崩溃记录,若需生成堆转储文件,可添加--hprof参数,并通过adb pull获取文件进行分析。
Q2: 如何确保Monkey测试只针对特定Activity?
A: 可通过-c参数指定Intent类别,例如adb shell monkey -c android.intent.category.LAUNCHER 100,或结合adb shell am start手动启动目标Activity后再执行Monkey测试。
