Swift2 UI测试-等待元素出现
我想暂停测试,等待一个元素出现在屏幕上,然后再继续 我看不到一个好的方法来创造一个期望,并等待使用Swift2 UI测试-等待元素出现,swift,swift2,xcode-ui-testing,Swift,Swift2,Xcode Ui Testing,我想暂停测试,等待一个元素出现在屏幕上,然后再继续 我看不到一个好的方法来创造一个期望,并等待使用 public func waitForExpectationsWithTimeout(timeout: NSTimeInterval, handler: XCWaitCompletionHandler?) 我一直使用的创建期望的方法是 public func expectationForPredicate(predicate: NSPredicate, evaluatedWithObject o
public func waitForExpectationsWithTimeout(timeout: NSTimeInterval, handler: XCWaitCompletionHandler?)
我一直使用的创建期望的方法是
public func expectationForPredicate(predicate: NSPredicate, evaluatedWithObject object: AnyObject, handler: XCPredicateExpectationHandler?) -> XCTestExpectation
但是这需要一个已经存在的元素,而我希望让测试等待一个还不存在的元素
有人知道这样做的最佳方法吗?它不需要已经存在的元素。您只需要定义以下谓词:
let exists=NSPredicate(格式:“exists=1”)
然后在你的期望中使用这个谓词。然后当然等待您的期望。在
expectationForPredicate(谓词:evaluatedWithObject:handler:)
中,您不提供实际的对象,而是提供一个查询以在视图层次结构中找到它。例如,这是一个有效的测试:
let predicate = NSPredicate(format: "exists == 1")
let query = XCUIApplication().buttons["Button"]
expectationForPredicate(predicate, evaluatedWithObject: query, handler: nil)
waitForExpectationsWithTimeout(3, handler: nil)
签出并从标题生成(目前没有正式文档),所有这些都是由Joe Masilotti编写的。您可以在Swift 3中使用这些标题
func wait(element: XCUIElement, duration: TimeInterval) {
let predicate = NSPredicate(format: "exists == true")
let _ = expectation(for: predicate, evaluatedWith: element, handler: nil)
// We use a buffer here to avoid flakiness with Timer on CI
waitForExpectations(timeout: duration + 0.5)
}
在Xcode 9、iOS 11中,您可以为Xcode 8.3使用新的API
waitForExistence
,以后您可以使用一个新类等待期望值-XCTWaiter
,示例测试如下所示:
func testExample() {
let element = // ...
let predicate = NSPredicate(format: "exists == true")
let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)
let result = XCTWaiter().wait(for: [expectation], timeout: 1)
XCTAssertEqual(.completed, result)
}
更多信息。基于我提出的扩展(Swift 3.2):
因此,在您的呼叫站点上,您可以使用:
wait(for: app.getElement(withIdentifier: "ViewController"), timeout: 10)
这个问题是关于Swift2的,但它仍然是2019年的热门搜索结果,所以我想给出一个最新的答案 使用Xcode 9.0+时,由于以下原因,事情变得简单了一点: 网络视图示例:
let app = XCUIApplication()
let webViewsQuery = app.webViews
let myButton = webViewsQuery.staticTexts["My Button"]
XCTAssertTrue(myButton.waitForExistence(timeout: 10))
sleep(1)
myButton.tap()
我在Objective-C中有一个例子,而不是在swift中。如果你需要的话,我可以把它包括在内。谢谢你的支持!我可以发誓我在早期版本的UI测试中尝试过这个,但没有成功,哦,好吧,感谢Xcode 8.3(目前仍然是beta版)有一个更好的方法可以做到这一点-XctestWater。发布时,我将更新我的答案。再次感谢您在本主题中提供了大量资源,我决定不更新当前答案,而是发布了一个新答案,以保留旧答案,原因是历史原因。请把标记看作是一个公认的答案。
let app = XCUIApplication()
let myButton = app.buttons["My Button"]
XCTAssertTrue(myButton.waitForExistence(timeout: 10))
sleep(1)
myButton.tap()
let app = XCUIApplication()
let webViewsQuery = app.webViews
let myButton = webViewsQuery.staticTexts["My Button"]
XCTAssertTrue(myButton.waitForExistence(timeout: 10))
sleep(1)
myButton.tap()