gpt4 book ai didi

swift - 如何测试异步方法的结果?

转载 作者:行者123 更新时间:2023-11-28 07:59:30 24 4
gpt4 key购买 nike

当我们获取 TableView 数据源时,我们会请求一个网络请求。它是异步的。我不知道要测试结果操作。有一种获取积分的方法。

     func loadPoints() {
API().retrievePoints{ [weak self](pointsSet, error) in
DispatchQueue.main.async(execute: {
// Make sure the call succeeded; return an error if it didn't
guard error == nil else {
self?.showErrorMessage()
Device.debugLog(item:"Error loading Points: \(String(describing: error))")
return
}

self?.pointsSet = pointsSet
self?.tableView.reloadData()
})
}
}

我知道如果我们想测试 retrievePoints 方法,我们可以像下面这样测试

//points
func testRetrievePoints() {
let expectation = self.expectation(description: "RetrievePoints")
API().retrievePoints{ (pointsSet, error) -> Void in
XCTAssertNil(pointsSet)
XCTAssertNotNil(error)
expectation.fulfill()
}
waitForExpectations(timeout: 15.0, handler: nil)
}

现在我要测试代码

         self?.pointsSet = pointsSet
self?.tableView.reloadData()

self?.showErrorMessage()

现在我只使用 sleep(15) 等待方法。但这是不准确的。请你帮助我好吗?提前致谢。

最佳答案

正如你所说的,它是异步的。所以完成之前需要时间。也就是说需要等待才能成功。另请注意,它只是超时值。您的所有任务都必须在此值内完成。否则视为失败。

关于swift - 如何测试异步方法的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47050896/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com