Xcode 14.3的XCUITests在iOS12设备上无法识别按钮求助
解决Xcode 14.3下iOS 12设备UITest点击按钮失败的问题
问题场景
升级到Xcode 14.3后,针对iOS 12设备的UITest执行按钮点击操作时抛出以下错误:
Invalid parameter not satisfying: allAttributesForKey != nil (NSInternalInconsistencyException)
相同测试代码在Xcode 14.2 + iOS 16环境下可正常运行,且因需测试iOS 16.4设备无法回退Xcode版本。
原测试代码
@discardableResult public func waitForButton(with identifier: String) -> XCUIElement { let button = app.buttons[identifier].firstMatch let predicate = NSPredicate(format: "exists == true") let expectation = expectation(for: predicate, evaluatedWith: button, handler: nil) let result = XCTWaiter.wait(for: [expectation], timeout: 15) XCTAssertEqual(result, .completed) return button } func testStart() throws { waitForButton(with: "Welcome.button").tap() // 此处执行失败 }
解决方案
方案1:改用waitForExistence并检查可交互性
Xcode 14.3的XCTest框架对firstMatch元素的属性处理在iOS 12上存在兼容性问题,直接等待元素存在且可点击可绕过该问题:
@discardableResult public func waitForButton(with identifier: String) -> XCUIElement { let button = app.buttons[identifier].firstMatch // 等待元素加载完成 XCTAssertTrue(button.waitForExistence(timeout: 15), "Button \(identifier) failed to appear within timeout") // 确保元素处于可交互状态 XCTAssertTrue(button.isHittable, "Button \(identifier) is not hittable") return button } func testStart() throws { waitForButton(with: "Welcome.button").tap() }
方案2:移除firstMatch并扩展等待条件
若方案1仍有问题,尝试直接使用元素查询结果,同时将等待条件扩展为「存在且可交互」:
@discardableResult public func waitForButton(with identifier: String) -> XCUIElement { let button = app.buttons[identifier] // 同时等待元素存在且可点击 let predicate = NSPredicate(format: "exists == true AND isHittable == true") let expectation = expectation(for: predicate, evaluatedWith: button, handler: nil) let result = XCTWaiter.wait(for: [expectation], timeout: 15) XCTAssertEqual(result, .completed) return button } func testStart() throws { waitForButton(with: "Welcome.button").tap() }
原因分析
Xcode 14.3对XCTest的底层属性获取逻辑做了调整,导致firstMatch返回的XCUIElement在iOS 12系统上无法正确获取属性集合,触发内部断言失败。通过调整等待逻辑确保元素处于稳定的可交互状态,可规避该兼容性问题。
内容的提问来源于stack exchange,提问作者skeg0
相关产品推荐
相关产品推荐

