异步swift单元测试被调用3次而不是1次

时间:2016-12-15 13:46:12

标签: ios swift unit-testing asynchronous xctestcase

我为异步函数编写了一个单元测试,它通过http请求加载数据。

当我开始测试时,它被调用3次而不是1次。

我试着像这里一样实现单元测试: https://adoptioncurve.net/archives/2015/10/testing-asynchronous-code-in-swift/

我的代码如下所示:

func getWatches(completionHandler: @escaping ((result:Bool)) -> ()) {

   Some code ... 

   URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in 

      Some code ...

      DispatchQueue.main.async(){
        completionHandler(true)
      }
   }).resume()
}



func testGetWatches() {
    let asyncExpectation = expectation(description: "longRunningFunction")

    WatchApiConnector.sharedInstance.getWatches() { (result) -> () in
        asyncExpectation.fulfill()
    }

    self.waitForExpectations(timeout: 5) { error in

        XCTAssertEqual(WatchApiConnector.sharedInstance.watches.count,20,"20 expected")

    }
}

结果我得到以下内容:

Test Suite 'WatchApiConnectorTests' passed at 2016-12-15 14:32:30.437.
     Executed 1 test, with 0 failures (0 unexpected) in 0.305 (0.306) seconds
Test Suite 'ChronextTests.xctest' passed at 2016-12-15 14:32:30.438.
     Executed 1 test, with 0 failures (0 unexpected) in 0.305 (0.307) seconds
Test Suite 'Selected tests' passed at 2016-12-15 14:32:30.439.
     Executed 1 test, with 0 failures (0 unexpected) in 0.305 (0.309) seconds

我做错了什么,或者这是iOS上异步单元测试的默认行为?

0 个答案:

没有答案