【问题标题】:completionHandler connot be executed in unit test of Xcode, ex. asynchronous api - reverseGeocodeLocation of CLGeocodercompletionHandler 不能在 Xcode 的单元测试中执行,例如。异步 api - CLGeocoder 的 reverseGeocodeLocation
【发布时间】:2015-08-10 13:59:43
【问题描述】:

我了解 CLGeocoder().reverseGeocodeLocation(...) 将在另一个线程中执行,因此一旦从 Apple 服务器成功获取结果,completionHandler 将在主线程中执行。问题是当我在单元测试中使用(当我构建框架时)时,我看不到完成处理程序中发生了什么,但它在应用程序中运行良好。为了简化我的问题,我从单元测试中的代码中提取异步部分,如下所示:

func testGeo() {
    var location = CLLocation(latitude: 45.0, longitude: 135.5)
    var semaphore = dispatch_semaphore_create(0)
    println("------fetch----->")
    CLGeocoder().reverseGeocodeLocation(location, completionHandler:{ (placemarks, error) -> Void in
        if error != nil {
            println("[ERROR]: \(error) in getPlacemarkFromLocation")
        }

        if placemarks.count > 0 {
            println("[SUCCESS] get the placemark!")
            let pm = placemarks[0] as! CLPlacemark
            self.displayLocationInfo(pm)
        } else {
            println("[ERROR] get 0 placemarks in getPlacemarkFromLocation")
        }
        dispatch_semaphore_signal(semaphore)
    })
    println("------wait--- -->")
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}

当我做这个单元测试时,它似乎没有执行 completionHandler,因为在控制台中没有任何东西可以打印。每次我使用异步api时,我的单元测试都无法成功获取返回值。我需要使用单元测试来确保我的框架的所有管道都运行良好。这会让我发疯......我该如何解决这个问题?非常感谢:)

【问题讨论】:

    标签: ios xcode swift asynchronous clgeocoder


    【解决方案1】:

    问题是因为测试函数在完成处理程序完成之前退出。

    从 Xcode 6 开始,Apple 发布了一个名为 XCTestExpectation 的异步测试工具。这件事使我们能够在超出范围之前等待一段时间。用法很简单:

        let expect = self.expectationWithDescription("exp")
        sc.asyncCall(para) { (data, error) in
    
            XCTAssertNotNil(data)
    
            expect.fulfill()
        }
    
        self.waitForExpectationsWithTimeout(1) { (error) in
            guard error == nil else {
                XCTAssert(false)
                NSLog("Timeout Error.")
                return
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-03
      • 2018-01-29
      相关资源
      最近更新 更多