Xcode 7/Swift 2.0 XCTestCase waitForExpectationsWithTimeout() EXC_BAD_ACCESS

Xcode 7/Swift 2.0 XCTestCase waitForExpectationsWithTimeout() EXC_BAD_ACCESS

我在 Xcode 7 中使用异步 Swift 2.0 代码实践测试驱动开发收效甚微。需要 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
    }
}

错误:

Thread 1: EXC_BAD_ACCESS(code=1, address=0x6.....)

当在异步执行的闭包之外满足期望 (expectation.fulfill()) 时,此测试将按预期通过(只要我注释掉闭包内的实现)。但这样做显然违背了同步测评的目的。

我会注意到,即使测试失败,Executed! 消息也会按预期打印。此外,如果在 waitForExpectationsWithTimeout... 行引入断点,则测试成功——类似地,引入人工睡眠延迟时测试成功。这让我相信 waitForExepectaionsWithTimeout() 根本没有等待。

诚然,我是 Xcode 和 Swift 的新手,所以如果我遗漏了一些明显的东西,我将不胜感激任何反馈。我上面的代码有什么问题?我可以提供任何环境变量来帮助调试问题吗?

运行:OS X El Capitan 10.11 测试版 (15A263e),Xcode 7.0 测试版 (7A120f)

我一直遇到同样的问题,不知道如何解决。我确保我的期望仍然得到分配,但它仍然失败了。所以我转向了另一种模式,使用调度组。 请参阅下面的示例和您的代码:

func testSomething(){
    let group = dispatch_group_create()
    dispatch_group_enter(group)

    let queue : dispatch_queue_t = dispatch_queue_create("async", nil);
    dispatch_async(queue, { () -> Void in
        print("Executed!")
        XCTAssert(true, "An aphorism about success.")
        dispatch_group_leave(group)
    })

    let wait_success = dispatch_group_wait(group, dispatch_time(DISPATCH_TIME_NOW,Int64(2*NSEC_PER_SEC)))
    XCTAssertEqual(wait_success, 0)
}

我当然更愿意使用标准的 waitForExpectation() 机制,但如果所有其他方法都失败了,那么它就可以正常工作