XCTest中waitForExistence执行逻辑疑问:等待时长如何计算?
XCTest中waitForExistence在逻辑或中的执行逻辑解析
你的代码执行逻辑是:先等待最多60秒判断aXCUIElement是否存在,只有当aXCUIElement在60秒后仍不存在时,才会继续等待最多60秒判断bXCUIElement是否存在。
原因解析
- Swift短路逻辑或特性:
||运算符是短路执行的——如果左侧表达式返回true,右侧表达式会直接被跳过,不会执行。 - waitForExistence的行为:
waitForExistence(timeout:)会从调用时刻开始,持续轮询元素是否存在,直到元素出现或超时时间耗尽,最终返回元素是否存在的布尔值。
两种典型场景
- 若
aXCUIElement在60秒内(比如第10秒)被检测到存在,左侧表达式返回true,右侧的bXCUIElement.waitForExistence不会被调用,整个判断立刻结束,总耗时约10秒。 - 若
aXCUIElement直到60秒后仍不存在,左侧返回false,才会执行右侧的bXCUIElement.waitForExistence,开始新一轮最多60秒的等待,总耗时最多可达120秒。
如果你需要“60秒内任意元素出现即停止等待”的逻辑
上面的写法无法实现这个需求,你可以用XCTest的期望机制来实现:
let existsPredicate = NSPredicate(format: "exists == true") let aExpectation = XCTNSPredicateExpectation(predicate: existsPredicate, object: aXCUIElement) let bExpectation = XCTNSPredicateExpectation(predicate: existsPredicate, object: bXCUIElement) // 等待任意一个期望满足,超时60秒 let waitResult = XCTWaiter().wait(for: [aExpectation, bExpectation], timeout: 60) if waitResult == .completed { // 任意元素已存在,执行后续操作 }
或者用自定义轮询的方式:
let totalTimeout = 60.0 let startDate = Date() var foundElement = false while Date().timeIntervalSince(startDate) < totalTimeout { if aXCUIElement.exists || bXCUIElement.exists { foundElement = true break } Thread.sleep(forTimeInterval: 0.5) // 降低轮询频率,避免资源消耗 } if foundElement { // 元素存在的处理逻辑 }
内容的提问来源于stack exchange,提问作者jacobcan118
相关产品推荐
相关产品推荐

