我已经为通过 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上异步单元测试的默认行为?