swift - 为什么这个 Swift 单元测试在与其他测试并行运行时会崩溃?

标签 swift unit-testing xctest xctestexpectation

我有一个单元测试,它在单独运行时成功,但在崩溃并出现EXC_BAD_ACCESS(大部分时间) >waitForExpectations 与其他测试一起运行时。

func testStartMonitoring() {

    let mockLocationManager = MockLocationManager()
    let beaconListener = BeaconListener(locationManager: mockLocationManager, uuid: BeaconListenerTests.defaultUUID)

    let e = self.expectation(description: "Expected beacons to be detected")

    //If the listener calls back, the expectation succeeds.
    beaconListener.didReceiveNewRoomInformation = { data in

        //There are three entries in the test data
        XCTAssert(data.count == 3)

        e.fulfill()
    }

    //Start listening
    beaconListener.startListening()

    //Wait up to 15s for a response
    self.waitForExpectations(timeout: 15.0, handler: {error in
        if let error = error {
            print("\(error)")
        }
    })
}

enter image description here enter image description here

  • 我没有其他异步测试
  • 测试不会因超时而失败
  • 由于测试仅在某些时候崩溃,我预计问题是某处的竞争条件,但我不确定要查找的位置。

我也可以用更简单的代码重现这个:

func testStartMonitoring() {

    let e = self.expectation(description: "Expected beacons to be detected")

    let deadlineTime = DispatchTime.now() + .seconds(1)
    DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
        e.fulfill()
    }

    //Wait up to 15s for a response
    self.waitForExpectations(timeout: 15.0, handler: {error in
    })
}

我从命令行运行测试并发现了这条额外的信息:

Error Domain=IDETestOperationsObserverErrorDomain Code=5 "Early unexpected exit, operation never finished bootstrapping - no restart will be attempted" UserInfo={NSLocalizedDescription=Early unexpected exit, operation never finished bootstrapping - no restart will be attempted}

其他一些答案表明这可能是由系统警报引起的。这是可以理解的,我正在使用需要权限警报的定位服务。但是,我运行测试的设备已经接受了权限,因此不应显示警报。

最佳答案

我有一个类似的问题 - 一组具有多个 expectations 的测试崩溃 - 并且遇到了你的问题。这让我意识到这是导致问题的权限 - 这里是位置管理器,我是语音识别。所以我模拟了我的授权请求类并注入(inject)了一个肯定的响应。

您必须搜索调用需要许可的任何方法 - 它们可能是也可能不是具有期望的方法。

关于swift - 为什么这个 Swift 单元测试在与其他测试并行运行时会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40584683/

相关文章:

java - Junit 框架单元测试 : Mockito. doNothing() 在模拟 void 方法时无法按预期工作

java - 创建 HttpServletRequest 和 HttpServletResponse 消息而不是模拟

java - Eclipse 中的“未找到 JUnit 测试”

objective-c - XCTAssertEqualObjects 比较 NSNumber 的 NSArrays 失败,即使数组看起来相同

c# - 在应用设置中同步应用版本和内部版本号

ios - UIButton 上的 UILongPressGestureRecognizer

ios - 如何使用 Swift 将多张图片上传到服务器?

ios - locationd 守护进程不断获取 jetsammed ios 8.1

c++ - 可以将 C++ 单元测试集成到 Xcode 的 XCTest 中吗?

xcode - Xcode 5.0.2 dyld:库未加载:@ rpath/XCTest.framework/Versions/A/XCTest