提问人:John Citrowske 提问时间:9/27/2023 更新时间:9/27/2023 访问量:49
在 Swift 中对异步函数进行单元测试
Unit testing an async function in Swift
问:
我正在尝试在我的 swift 项目中测试异步函数,但我在测试的倒数第二行收到此错误 -> 线程 1:“在已失效的会话中创建的任务”wait(for: [expectation], timeout: 20.0)
我知道 API 可以工作并返回数据,因为它在运行项目和在 Postman 中工作。
这是单元测试
func testRswPrice(){
//Given (Arrange)
let fromLat = 26.336502
let fromLon = -81.439354
let toLat = 26.533842
let toLon = -81.759150
let vm = LocationSearchViewModel()
//When (Act)
let expectation = self.expectation(description: "Compute Price")
vm.computePrice(fromLat, fromLon, toLat, toLon){ value in
expectation.fulfill()
XCTAssertEqual(value, 8000.0)
}
// Wait for the expectation to be fulfilled, or time out after a specified duration
wait(for: [expectation], timeout: 20.0)
}
这是 vm 内部的功能
func computePrice(_ fromLat: Double, _ fromLon: Double,_ toLat: Double, _ toLon: Double, completion: @escaping (Double?) -> Void){
let url = URL(string:"NotShowingMyUrlToStackOverflowButPretendItsHere")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
print("fromLat: \(fromLat) fromLon: \(fromLon) toLat: \(toLat) toLon: \(toLon)")
let body = [
"from": [
"latitude": fromLat,
"longitude": fromLon
],
"to": [
"latitude": toLat,
"longitude": toLon
]
]
let jsonData = try? JSONSerialization.data(withJSONObject: body)
request.httpBody = jsonData
URLSession.shared.dataTask(with: request){ data, response, error in
guard let data = data, error == nil,
(response as? HTTPURLResponse)?.statusCode == 200
else{
completion(nil)
return
}
//Decode JSON response
do {
let decoder = JSONDecoder()
let response1 = try decoder.decode(PriceResponse.self, from: data)
DispatchQueue.main.async {
completion(response1.price)
self.screenDisabled = false
}
} catch {
DispatchQueue.main.async {
self.showingInvalidAlert = true
}
print("THE ERROR IS \(error.localizedDescription)")
}
}.resume()
}
答: 暂无答案
评论
DispatchQueue.main.async