测试与性能
测试与性能 · androidx.test
UI Automator:跨越应用边界
用设备级选择器操作系统界面和多应用流程,并控制脆弱性。
最后更新 2026-08-01
复制即用
@get:Rule
val deviceRule = UiDeviceRule() // 或手动 getInstance
@Test
fun openSystemSettings() {
val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
device.pressHome()
device.executeShellCommand("am start -a android.settings.SETTINGS")
device.wait(Until.hasObject(By.text("设置")), 5_000)
device.findObject(By.text("设置")).click()
}选择器 API
| API | 用途 |
|---|---|
By.text("...") | 文本(随语言变化,慎用) |
By.res("pkg:id/name") | 资源 id(推荐) |
By.desc("...") | 无障碍描述 |
By.pkg("com.android.settings") | 包名 |
By.clazz("android.widget.Button") | 类名 |
By.textContains("...") / By.descContains("...") | 模糊匹配 |
By.allOf(sel1, sel2) | 组合条件 |
设备级操作
device.pressHome()
device.pressBack()
device.pressRecentApps()
device.swipe(x1, y1, x2, y2, steps)
device.click(x, y) // 坐标点击,最后手段
device.wait(Until.hasObject(selector), timeout)
device.waitForIdle()跨应用流程
UI Automator 在设备层工作,适合权限对话框、系统设置、通知栏以及跨应用流程。只测试自己应用内部 View 或 Compose 语义时,Espresso/Compose UI Test 通常更快、更稳定。
常见陷阱
- 坐标点击:分辨率、语言、字体、系统版本都会破坏,优先资源 id + 无障碍描述。
- 依赖系统文本:固定测试设备 locale 或使用稳定资源标识。
- 外部状态泄漏:结束时清理通知、旋转锁定、测试账户。
- 每轮不确定起点:测试开始把设备带到已知状态。
要点
- 设备层工作:权限对话框、系统设置、通知栏、跨应用流程。
- 选择器组合:资源 id + 无障碍描述 + 稳定文本。
- 开始带设备到已知状态,结束清理外部状态。
- 应用内测试用 Espresso/Compose UI Test 更快更稳。