无法转换类型'(数据?) - >的值()'预期参数类型'(_) - > ()'

时间:2018-03-01 20:35:57

标签: ios swift unit-testing

我创建了一个从网络服务器检索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)

}

1 个答案:

答案 0 :(得分:0)

问题是,完成返回MainColor类型而不是Data的值,这应该是

var actualData: MainColor?