ios - 如何测试 UIControlEvents 是否已被触发

标签 ios swift selector xctest nsrunloop

我有一个实现自定义 UIControl 的库,它的方法会在调用时触发 .valueChanged 事件。我想测试该行为的方法。

我的自定义控件:

class MyControl: UIControl {
    func fire() {
        sendActions(for: .valueChanged)
    }
}

和测试:

import XCTest

class ControlEventObserver: NSObject {
    var expectation: XCTestExpectation!

    init(expectation anExpectation: XCTestExpectation) {
        expectation = anExpectation
    }

    func observe() {
        expectation.fulfill()
    }
}

class Tests: XCTestCase {
    func test() {
        let myExpectation = expectation(description: "event fired")
        let observer = ControlEventObserver(expectation: myExpectation)
        let control = MyControl()
        control.addTarget(observer, action: #selector(ControlEventObserver.observe), for: .valueChanged)
        control.fire()
        waitForExpectations(timeout: 1) { error in
            XCTAssertNil(error)
        }
    }
}

问题是 observe 方法永远不会被调用,所以 expectation 没有实现。

问题是:在这种情况下,我们如何测试 UIControlEvents?也许我们需要以某种方式强制运行循环?

编辑 1: 请注意,因为我正在测试一个库,所以我的测试目标没有任何主机应用程序。当测试目标有一个主机应用程序时,上面的测试通过。

最佳答案

Apple's documentation for UIControl指出:

When a control-specific event occurs, the control calls any associated action methods right away. Action methods are dispatched through the current UIApplication object, which finds an appropriate object to handle the message, following the responder chain if needed.

当在 UIControl 上调用 sendActions(for:) 时,该控件将调用 UIApplicationsendAction(_:to:from:for: ) 将事件传递给注册的目标。

因为我正在测试一个没有任何主机应用程序的库,所以没有 UIApplication 对象。因此,不会调度 .valueChanged 事件,也不会调用 observe 方法。

关于ios - 如何测试 UIControlEvents 是否已被触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851205/

相关文章:

ios - 如何将图像随机链接到声音?

jquery - 何时使用 $(this) 不是更慢吗?

jQuery - 如何匹配具有属性 a 或属性 b 的元素

ios - Xcode Playground 不显示在右侧

ios - 自定义标签未显示在自定义单元格中。 Storyboard

ios - 无法将应用程序提交到 AppStore。 "Your application bundle' s 签名包含 iOS 不支持的代码签名权利”

ios - 在 iOS 应用程序中加载谷歌地图的高内存使用率

ios - Swift 2.1 iOS 启动时结构中的静态 bool 值设置为错误值

android - 可以用选择器绘制吗?

ios - TableView 单元格操作