如何测试是否已触发UIControlEvents [英] How to test if a UIControlEvents has been fired

查看:180
本文介绍了如何测试是否已触发UIControlEvents的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a library implementing a custom UIControl with a method which would fire a .valueChanged event when called. I would like to test the method for that behavior.

我的自定义控件:

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 方法永远不会被调用所以预期未履行。

The problem is the observe method never gets called so the expectation is not fulfilled.

问题是:我们如何测试 UIControlEvents 喜欢这种情况?也许我们需要以某种方式强制运行runloop?

The question is: how can we test for UIControlEvents like in this case? Perhaps we need to force the runloop somehow?

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

EDIT 1: Please note that since I am testing a library, my test target does not have any Host Application. The test above passes when the test target has a host application.

推荐答案

Apple的UIControl文档指出:


当a控件特定事件发生时,控件立即调用任何关联的
操作方法。 通过
当前UIApplication对象
调度操作方法,该对象找到
处理消息的适当对象,如果需要,在响应者链之后。

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 :) 时,控件将调用 UIApplication sendAction(_:to:from:for:)将事件传递给注册目标。

When sendActions(for:) is called on a UIControl, the control will call the UIApplication's sendAction(_:to:from:for:) to deliver the event to the registered target.

由于我在没有任何Host Application的情况下测试库,因此没有 UIApplication 对象。因此,不会调度 .valueChanged 事件,并且不会调用 observe 方法。

Since I am testing a library without any Host Application, there is no UIApplication object. Hence, the .valueChanged event is not dispatched and the observe method does not get called.

这篇关于如何测试是否已触发UIControlEvents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆