【发布时间】:2015-11-15 21:08:17
【问题描述】:
我在 Xcode 7 中使用异步 Swift 2.0 代码实践测试驱动开发几乎没有成功。我唯一成功的解决方案是人为的和 hacky 的延迟机制,它回避了对 waitForExepectationsWithTimeout() 的需求。我想按如下方式执行异步测试,但此代码始终失败:
import Foundation
import XCTest
class AsyncTest : XCTestCase {
func testAsync() {
let expectation : XCTestExpectation = self.expectationWithDescription("That waitForExpectationsWithTimeout() will actually wait.")
let queue : dispatch_queue_t = dispatch_queue_create("async", nil);
dispatch_async(queue, { () -> Void in
print("Executed!")
XCTAssert(true, "An aphorism about success.")
expectation.fulfill()
})
waitForExpectationsWithTimeout(100.0, handler: nil) // Arbitrary wait period of 100
}
}
错误:
线程 1:EXC_BAD_ACCESS(code=1, address=0x6.....)
当期望在异步执行的闭包之外实现(expectation.fulfill())时,这个测试将按预期通过(只要我注释掉闭包内的实现)。但这样做显然违背了同步测试评估的目的。
我会注意到,即使测试失败,Executed! 消息也会按预期打印。此外,如果在waitForExpectationsWithTimeout... 行上引入断点,则测试成功——类似地,当引入人工睡眠延迟时测试成功。这让我相信waitForExepectaionsWithTimeout() 根本没有在等待。
诚然,我是 Xcode 和 Swift 的新手,所以如果我遗漏了一些明显的东西,我将非常感谢任何反馈。我上面的代码有什么问题?我可以提供任何环境变量来帮助调试问题吗?
运行:OS X El Capitan 10.11 Beta (15A263e)、Xcode 7.0 beta (7A120f)
【问题讨论】:
-
崩溃是仅通过 Xcode IDE 发生还是在您通过 xcodebuild 在 CLI 上运行测试时发生?
标签: xcode swift asynchronous osx-elcapitan