我无法正确进行单元测试,我想检查数据是否在我的结构中,我可以使用我的函数打印出有多少项但是测试失败因为期望没有到来背部。 我知道我需要使用
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
}
}
答案 0 :(得分:2)
您已经成功地证明了为什么单元测试是一个好主意。
您在getPlayer
方法中发现了一个严重错误 - 您从未调用完成处理程序。
您应该使用completionHandler
方法中不同位置的相应参数调用getPlayer
闭包,具体取决于您是否成功处理数据或遇到错误。