2016-12-06 149 views
0

我無法正確獲取我的單元測試,我想檢查它的數據是否在我的結構中,我可以讓我的函數打印出有多少項目,但測試失敗,因爲期望不會回來。 我知道我需要使用Swift單元測試:異步

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 
    } 
} 

回答

2

您已經成功地證明了爲什麼單元測試是一個好主意。

您在getPlayer方法中發現了一個嚴重的錯誤 - 您永遠不會調用完成處理程序。

根據您是成功處理數據還是遇到錯誤,您應該使用getPlayer方法中各個地方的適當參數調用completionHandler閉包。