【问题标题】:Xcode 7/Swift 2.0 XCTestCase waitForExpectationsWithTimeout() EXC_BAD_ACCESSXcode 7/Swift 2.0 XCTestCase waitForExpectationsWithTimeout() EXC_BAD_ACCESS
【发布时间】: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


【解决方案1】:

我遇到了同样的问题,不知道如何让它工作。我确保我的期望仍然得到分配,但它仍然失败了。所以我通过使用调度组转向了不同的模式。 请参阅下面的示例代码:

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() 机制,但如果所有其他方法都失败了,那么它就可以了

【讨论】:

  • 我已经测试了您的解决方案并且它有效,但请注意,从 XCode 版本 7.2 (7C68) 和 OS X 10.11.3 Beta (15D13b) 开始,我的原始解决方案不再出现错误代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-20
  • 2015-09-14
相关资源
最近更新 更多