swift - 以编程方式触发 UIAlertController 上的 UIAlertAction?

标签 swift unit-testing uialertcontroller uialertaction

关于这个主题有几个现有的问题,但它们并不是我想要的。我为我的应用程序编写了一个 Swift 应用程序评级小提示,其中显示两个 UIAlertController实例,一个由另一个触发。

我现在正尝试对此进行单元测试,并尝试在测试中达到第二个警报。我已经编写了一个简单的 spy 程序来检查第一个 Controller ,但我想要一种方法来触发第一个警报中的一个操作,然后显示第二个警报。

我已经试过了 alert.actions.first?.accessibilityActivate() ,但它似乎并没有破坏该操作的处理程序 - 这就是我所追求的。

最佳答案

一种不涉及更改生产代码以允许在单元测试中以编程方式点击 UIAlertActions 的解决方案,这是我发现的 in this SO answer .

在谷歌搜索答案时将其张贴在这里以及为我弹出的这个问题,以下解决方案花了我更多时间来寻找。

在您的测试目标中放入以下扩展:

extension UIAlertController {
    typealias AlertHandler = @convention(block) (UIAlertAction) -> Void

    func tapButton(atIndex index: Int) {
        guard let block = actions[index].value(forKey: "handler") else { return }
        let handler = unsafeBitCast(block as AnyObject, to: AlertHandler.self)
        handler(actions[index])
    }
}

关于swift - 以编程方式触发 UIAlertController 上的 UIAlertAction?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36173740/

相关文章:

ios - 设置 UITableView 使用的数组索引的不同方法

swift - 如何在表格 View 单元格swift 3中将当前时间添加到标签

swift - 初始化(编码器 :) has not been implemented in swift

swift - 从 UIAlertAction 获取 UIAlertController?

ios - 在 iOS8 中自定义 UIAlertController

ios - MicroBlink SDK 的 USDL 组合识别器 documentDataMatch 返回始终 true

javascript - 我们可以将 before 和 after block 写入 mocha 的特定测试用例(it)吗

unit-testing - 在Visual Studio测试中,如何制作自动排除某些测试的播放列表?

visual-studio-2010 - 单元测试在调试中通过,但在运行时挂起

ios - UIAlertController 的后续演示出现卡顿