我正在编写单元测试来测试我的网络服务调用。问题是所有调用都取决于 token (我在登录后获得)。在设置方法中,我调用了登录,但由于它是异步调用,在设置 token 之前,我的测试方法被调用并且它在 token 中为空。有几种解决方案(在测试我的实际服务之前设置任意 token 或调用登录)。我想要更好的解决方案来处理这件事。有什么建议吗?
谢谢。
最佳答案
使用 XCTest,您可以让测试等待异步调用返回。您可以使用它来检索setUp中的 token ,并在测试中使用该 token :
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
}
}
关于iOS 单元测试依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32241736/