在 XCode UI 测试中等待所有 HTTP 请求完成?
Wait for all HTTP requests to finish in XCode UI tests?
在 XCode 中测试 UI 时,是否有等待所有网络请求完成的方法?
我有一个应用程序发送 HTTP 请求以从服务器获取一些数据,并且在 UI 测试中,我想在继续之前等待检索到这些数据。目前我正在使用 sleep(1)
但这种方法似乎不可靠。
您可以使用委托或完成块设置您的方法,并在您的测试用例中使用 XCTestExpectation
,当数据返回时您可以 fulfill
。
最好的办法是等待某些 UI 元素出现或消失。这样想:
The framework acts like a user. It doesn't care what code is running under the hood. The only thing that matters is what is visible on the screen.
就是说,这里是您可以在 UI 测试中 wait for a label titled "Go!" to appear 的方法。
let app = XCUIApplication()
let goLabel = self.app.staticTexts["Go!"]
XCTAssertFalse(goLabel.exists)
let exists = NSPredicate(format: "exists == true")
expectationForPredicate(exists, evaluatedWithObject: goLabel, handler: nil)
app.buttons["Ready, set..."].tap()
waitForExpectationsWithTimeout(5, handler: nil)
XCTAssert(goLabel.exists)
你也可以extract that into a helper method。如果您使用一些 Swift 编译器魔术,您甚至可以在 调用 方法的行上获得失败消息。
private fund waitForElementToAppear(element: XCUIElement, file: String = #file, line: UInt = #line) {
let existsPredicate = NSPredicate(format: "exists == true")
expectationForPredicate(existsPredicate, evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(5) { (error) -> Void in
if (error != nil) {
let message = "Failed to find \(element) after 5 seconds."
self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
}
}
}
在 XCode 中测试 UI 时,是否有等待所有网络请求完成的方法?
我有一个应用程序发送 HTTP 请求以从服务器获取一些数据,并且在 UI 测试中,我想在继续之前等待检索到这些数据。目前我正在使用 sleep(1)
但这种方法似乎不可靠。
您可以使用委托或完成块设置您的方法,并在您的测试用例中使用 XCTestExpectation
,当数据返回时您可以 fulfill
。
最好的办法是等待某些 UI 元素出现或消失。这样想:
The framework acts like a user. It doesn't care what code is running under the hood. The only thing that matters is what is visible on the screen.
就是说,这里是您可以在 UI 测试中 wait for a label titled "Go!" to appear 的方法。
let app = XCUIApplication()
let goLabel = self.app.staticTexts["Go!"]
XCTAssertFalse(goLabel.exists)
let exists = NSPredicate(format: "exists == true")
expectationForPredicate(exists, evaluatedWithObject: goLabel, handler: nil)
app.buttons["Ready, set..."].tap()
waitForExpectationsWithTimeout(5, handler: nil)
XCTAssert(goLabel.exists)
你也可以extract that into a helper method。如果您使用一些 Swift 编译器魔术,您甚至可以在 调用 方法的行上获得失败消息。
private fund waitForElementToAppear(element: XCUIElement, file: String = #file, line: UInt = #line) {
let existsPredicate = NSPredicate(format: "exists == true")
expectationForPredicate(existsPredicate, evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(5) { (error) -> Void in
if (error != nil) {
let message = "Failed to find \(element) after 5 seconds."
self.recordFailureWithDescription(message, inFile: file, atLine: line, expected: true)
}
}
}