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

Ios 异步swift单元测试被调用3次而不是1次,ios,swift,unit-testing,asynchronous,xctestcase,Ios,Swift,Unit Testing,Asynchronous,Xctestcase,我已经为一个异步函数编写了一个单元测试,该函数通过http请求加载数据 当我开始测试时,它会被呼叫3次而不是1次 我尝试实现如下单元测试: 我的代码如下所示: func getWatches(completionHandler: @escaping ((result:Bool)) -> ()) { Some code ... URLSession.shared.dataTask(with: request, completionHandler: { (data, res

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

当我开始测试时,它会被呼叫3次而不是1次

我尝试实现如下单元测试:

我的代码如下所示:

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

嗯,这似乎是项目结构的问题,而不是代码的问题。您的项目中是否有3个测试目标?这三个测试类都包括这个测试类吗?不,我使用一个测试目标进行单元测试,一个用于UI测试。此测试用例还以一个测试目标为目标。测试时您是否碰巧运行了所有测试目标?它们都包含一个测试用例吗?不,我只运行测试函数,甚至不运行整个目标。但是,当我在我的目标中运行所有测试时,它会被调用3次,在这个问题上没有解决方案?嗯,这似乎是项目结构的问题,而不是代码的问题。您的项目中是否有3个测试目标?这三个测试类都包括这个测试类吗?不,我使用一个测试目标进行单元测试,一个用于UI测试。此测试用例还以一个测试目标为目标。测试时您是否碰巧运行了所有测试目标?它们都包含一个测试用例吗?不,我只运行测试函数,甚至不运行整个目标。但是当我在我的目标中运行所有测试时,它会被称为3次没有解决方案?