我正在编写单元测试来测试我的web服务调用。问题是所有的呼叫都依赖于令牌(这是我登录后得到的)。在setup方法中,我调用了登录,但由于它是异步调用,在设置令牌之前,我的测试方法被调用,它在令牌中得到null。有两种解决方案(在测试实际服务之前设置任意令牌或呼叫登录)。我想要更好的解决方案来处理这件事。有什么建议吗?
谢谢。
发布于 2015-08-27 15:48:39
使用XCTest,您可以让测试等待异步调用返回。您可以使用此命令在setUp中检索令牌,并在测试中使用该令牌:
class MyTestCase: XCTestCase {
var token: String?
override func setUp() {
if token != nil {
let expectation = expectationWithDescription("login")
webService.login { (resultToken) -> Void in
token = resultToken
expectation.fulfill()
}
// this will wait until expectation is fulfilled or the timeout (30 secs) is exceeded (will trigger error)
waitForExpectationsWithTimeout(30, handler: nil)
}
}
func testThatMyFeatureWorks() {
// here you can use the token
}
}https://stackoverflow.com/questions/32241736
复制相似问题