我在 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(代码=1,地址=0x6.....)
当期望expectation.fulfill()
在异步执行的闭包之外实现()时,这个测试将按预期通过(只要我注释掉闭包内的实现)。但这样做显然违背了同步测试评估的目的。
我会注意到,即使测试失败,Executed!
消息也会按预期打印。此外,如果在线路上引入断点waitForExpectationsWithTimeout...
,则测试成功——类似地,当引入人工睡眠延迟时,测试成功。这让我相信那waitForExepectaionsWithTimeout()
根本不是等待。
诚然,我是 Xcode 和 Swift 的新手,所以如果我遗漏了一些明显的东西,我将非常感谢任何反馈。我上面的代码有什么问题?我可以提供任何环境变量来帮助调试问题吗?
运行:OS X El Capitan 10.11 Beta (15A263e)、Xcode 7.0 beta (7A120f)