我在 UI 测试中使用了自定义等待,它始终有效(我为 XCTestCase 创建了一个扩展):
public class var defaultTimeOut: TimeInterval { return 5 }
public func wait(forFulfillmentOf predicate: NSPredicate,
for element: XCUIElement,
withFailingMessage message: String = "Failed to fulfill predicate %@ for %@ within %.2f seconds.",
timeout: TimeInterval = XCTestCase.defaultTimeOut,
file: StaticString = #file,
line: UInt = #line) {
expectation(for: predicate, evaluatedWith: element, handler: nil)
waitForExpectations(timeout: timeout) { (error) -> Void in
guard error != nil else {
return
}
let failingMessage = String(format: message, arguments: [predicate, element, timeout])
self.recordFailure(withDescription: failingMessage, inFile: String(describing: file), atLine: Int(clamping: line), expected: true)
}
}
那么你就可以在 UI 测试中实际使用这个方法了:
public func wait(forExistanceOf element: XCUIElement, timeout: TimeInterval = XCTestCase.defaultTimeOut, file: StaticString = #file, line: UInt = #line) {
let existancePredicate = NSPredicate(format: "exists == true")
wait(forFulfillmentOf: existancePredicate, for: element, withFailingMessage: "Failed to find %2$@ within %3$.2f seconds. Predicate was: %1$@.", timeout: timeout, file: file, line: line)
}
希望这会有所帮助!