XCUITest如何定位iOS的StatusBar以校验其显隐状态?
XCUITest定位StatusBar的解决方案
问题原因
iOS 13及以上系统对状态栏的管理逻辑做了重构,StatusBar属于系统进程SpringBoard管辖,不再内嵌到普通App的视图层级中,所以直接在当前测试的XCUIApplication实例下查找StatusBar会返回空结果。
正确实现步骤
- 针对不同iOS版本做兼容处理,iOS13+从系统SpringBoard进程获取StatusBar元素,iOS12及以下仍从当前App实例获取
- 组合使用
exists和isHittable属性判断可见性,避免误判 - 完整示例代码如下:
func testCheckStatusBarVisibility() throws { let testApp = XCUIApplication() testApp.launch() let statusBar: XCUIElement if #available(iOS 13.0, *) { // 获取系统SpringBoard应用实例 let springBoard = XCUIApplication(bundleIdentifier: "com.apple.springboard") statusBar = springBoard.statusBars.firstMatch } else { statusBar = testApp.statusBars.firstMatch } // 验证状态栏可见 XCTAssertTrue(statusBar.exists && statusBar.isHittable) // 若需验证状态栏隐藏,替换为以下断言 // XCTAssertFalse(statusBar.exists && statusBar.isHittable) }
注意事项
- XCUITest默认拥有访问SpringBoard进程的权限,无需额外配置
- 不要使用
element(boundBy: 0),优先使用firstMatch提升查找效率,避免无意义的全量元素遍历
内容的提问来源于stack exchange,提问作者Jens Schwarzer
相关产品推荐
相关产品推荐

