我创建了一个从网络服务器检索json数据的函数。它在生产环境中运行时可正常工作,但在设置为单元测试时,错误为Cannot convert value of type '(Data?) -> ()' to expected argument type '(_) -> ()'
。这是功能:
func getJSONData <T : Codable> (url: ServerUrl, type: T.Type, completionHandler:@escaping (_ details: T) -> ()) {
guard let url = URL(string: baseURL + url.rawValue) else { return }
session.dataTask(with: url, completionHandler: {
(data, response, err) in
guard err == nil else {
print("There was a network error:", err as Any)
return
}
guard let data = data else { return }
do {
let updatedModels = try JSONDecoder().decode(T.self, from: data)
completionHandler(updatedModels)
} catch let jsonErr {
print("Error serializing json:", jsonErr)
return }
}).resume()
}
这是单元测试:
func test_getJSONData_should_return_data() {
var actualData: Data?
sut.getJSONData(url: ServerUrl.colors, type: MainColor.self, completionHandler: { (data) in //error here
actualData = data
})
XCTAssertNotNil(actualData)
}
答案 0 :(得分:0)
问题是,完成返回MainColor
类型而不是Data
的值,这应该是
var actualData: MainColor?