XCTestCase setUp一次使用异步操作

时间:2015-07-01 13:58:08

标签: objective-c xcode swift unit-testing xctest

我正在尝试为使用Web服务API的iOS客户端编写一些单元测试。我想使用实际的服务,而不是模拟数据。

在所有测试都可以运行之前,我需要获取一个令牌来验证用户身份。 我正在尝试使用类setUp方法来执行此操作 - 但我不确定如何在继续其余测试之前等待令牌到达(因为所有网络调用都是异步的) )。

1 个答案:

答案 0 :(得分:0)

您可以创建一个等待令牌的函数,使用虚拟(内部无验证)assync测试,如下所示:

 func waitforToken(){
    let dummyExpectation = expectationWithDescription("Expect to get my token")
    ... call web service

    waitForExpectationsWithTimeout(20, handler: { error in
         XCTAssertNil(error, "Error")
    })
}
//on the web service Callback fulfill the expectation
func webServiceCallback(expectation:expectationWithDescription, ...)  {
   ...
   expectation.fulfill()
}

然后在每次测试开始时调用它。如果你在setUp内打电话,可能不会工作,但我可能错了。