gpt4 book ai didi

Swift 单元测试 : async

转载 作者:行者123 更新时间:2023-11-28 12:35:42 25 4
gpt4 key购买 nike

我在正确进行单元测试时遇到问题,我想检查它的数据是否在我的结构中,我可以让我的函数打印出有多少项目但是测试失败了,因为期望没有出现后退。我知道我需要使用

XCTAssertNotNil(self.players.countPlayers)

这是我的函数标题

public func getPlayer(completionHandler: @escaping (Data?, URLResponse?, Error?) -> (Swift.Void)
) throws{
let jsonUrl: String = "http://api.football-data.org/v1/teams/78/players"
//print(jsonUrl)
// NSURL sessions allow us to download data using HTTP for APIs
// a NSURL which contains a correct resourse
guard let leagueURL = NSURL(string: jsonUrl)else{
print("error creating string")
throw JSONError.InvalidURL(jsonUrl)
}
let task = URLSession.shared.dataTask(with: leagueURL as URL) {data, responce, error in

do {
let json = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
self.searchLeague = []
for item in json["players"] as! [[String: AnyObject]]{
guard let name = ((item["name"]!) as? String) else{
throw JSONError.InvalidKey("invalid player name")
}
guard let position = ((item["position"]!) as? String) else{
throw JSONError.InvalidKey("invalid player position")
}
let jerseyNumber = ( ((item["jerseyNumber"]!) as? String) ?? ("No Assigned jersey number") )

guard let dateOfBirth = ((item["dateOfBirth"]!) as? String) else{
throw JSONError.InvalidKey("invalid player DOB")
}
guard let nationality = ((item["nationality"]!) as? String) else{
throw JSONError.InvalidKey("invalid player DOB")
}
let marketvalue = ( ((item["marketValue"]!) as? String) ?? ("Market value info not available"))
self.searchPlayer.append(Player(name: name, position: position, jerseyNumber: jerseyNumber, dateOfBirth: dateOfBirth, nationality: nationality, marketValue: marketvalue))
}
}catch{
print("error thrown: \(error)")
}
print("Num of Players \(self.searchPlayer.count)")
}
task.resume()

}

和我的测试

    func testGetPlayers(){
let expectations = expectation(description: "Wait for exception")
try! self.players.getPlayer{_,_,_ in
expectations.fulfill()
}
waitForExpectations(timeout: 5) { error in
}
}

最佳答案

您已经成功地证明了为什么单元测试是个好主意。

您在 getPlayer 方法中发现了一个严重的错误 - 您从未调用完成处理程序。

您应该使用 getPlayer 方法中不同位置的适当参数调用 completionHandler 闭包,具体取决于您是成功处理数据还是遇到错误。

关于Swift 单元测试 : async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985636/

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