处理UI测试Swift中来自API的答案



我有天气应用程序。它从API获取数据。我输入需要的城市,然后下一个屏幕打开并显示城市名称和温度。我正在编写UI测试,它应该打开应用程序,处理一个要求使用位置的警报,然后测试应该写城市名称并检查这个城市是否存在于屏幕上。所有的工作,除了检查城市名称在最后。我认为问题可能是因为它需要一些时间才能从API获得答案,而测试没有等待它。也许我需要设置计时器来等待答案。或问题是smth别的吗?这是我的代码,它在最后一行失败了。

func testExample() throws {

let app = XCUIApplication()
app.launchArguments = ["enable-testing"]
app.launch()

app/*@START_MENU_TOKEN@*/.staticTexts["My location"]/*[[".buttons["My location"].staticTexts["My location"]",".staticTexts["My location"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap()
addUIInterruptionMonitor(withDescription: "Allow “APP” to access your location?") { (alert) -> Bool in
let button = alert.buttons["Only While Using the App"]
if button.exists {
button.tap()
return true // The alert was handled
}
return false // The alert was not handled
}

app.textFields["Enter your city"].tap()
app.textFields["Enter your city"].typeText("Barcelona")

app.buttons["Check weather"].tap()

XCTAssertTrue(app.staticTexts["Barcelona"].exists)

}

XCTest带有您需要的内置函数

文档:https://developer.apple.com/documentation/xctest/xcuielement/2879412-waitforexistence/

的例子:XCTAssertTrue(myButton.waitForExistence(timeout: 3), "Button did not appear")

我找到了这个函数并使用它来等待结果。下面是这个函数及其在我的代码中的用法。

func waitForElementToAppear(_ element: XCUIElement) -> Bool {
let predicate = NSPredicate(format: "exists == true")
let expectation = expectation(for: predicate, evaluatedWith: element,
handler: nil)
let result = XCTWaiter().wait(for: [expectation], timeout: 5)
return result == .completed
}

app.textFields["Enter your city"].tap()
app.textFields["Enter your city"].typeText("Barcelona")
app.buttons["Check weather"].tap()
let result = app.staticTexts["Barcelona"]
waitForElementToAppear(result)
XCTAssertTrue(result.exists)

最新更新