UIAlertController 测试的修正

作者:dom,原文链接,原文日期:2015-11-25
译者:小袋子;校对:lfb_CD;定稿:千叶知风

两个月前,我曾发布了一篇如何测试 UIAlertController文章一个读者发现测试没有如期地起作用:

@dasdom 你的测试是正常的,但是在 MockUIAction 中的简便 init 方法没有被调用。你不能重写 init 方法,看起来像是 iOS 的bug。
— Larhythimx (@Larhythmix) 25. November 2015

Larhythimx 说的完全正确。模拟程序的初始化方法从来没有调用。为什么我在写这个测试用例的时候没有发觉呢?那是因为 handler 确实被调用了,看起来就像 UIAlertAction 真的把 handler 作为内部变量去存储动作的 handler 闭包。这是非常脆弱的,并且 Larhythimx 在另一个 tweet 指出在他的测试程序中 handler 是 nil

所以作为黄金通道(即编写不需要改变实现的测试)走不通,那就退而求其次用别的方法

首先,我们在 UIAlertAction添加一个方法去创建 action 。在 ViewController.swift增加如下扩展:

extension UIAlertAction {
  class func makeActionWithTitle(title: String?,style: UIAlertActionStyle,handler: ((UIAlertAction) -> Void)?) -> UIAlertAction {
    return UIAlertAction(title: title,style: style,handler: handler)
  }
}

MockAlertAction增加这个重写方法

override class func makeActionWithTitle(title: String?,handler: ((UIAlertAction) -> Void)?) -> MockAlertAction {
  return MockAlertAction(title: title,handler: handler)
}

在实现代码中,我们现在可以使用类方法去创建 alert 动作:

let okAction = Action.makeActionWithTitle("OK",style: .Default) { (action) -> Void in
    self.actionString = "OK"
}
let cancelAction = Action.makeActionWithTitle("Cancel",style: .Default) { (action) -> Void in
    self.actionString = "Cancel"
}
alertViewController.addAction(cancelAction)

为了确保我们的测试用例正常,如我们预期地工作,将 MockAlertActionhandler 属性重命名mockHandler

var mockHandler: Handler?

此外,我们为动作的模拟标题添加测试。取消动作的测试应该像这样:

func testAlert_FirstActionStoresCancel() {
  sut.Action = MockAlertAction.self
  
  sut.showAlert(UIButton())
  
  let alertController = sut.presentedViewController as! UIAlertController
  let action = alertController.actions.first as! MockAlertAction
  action.mockHandler!(action)
  
  XCTAssertEqual(sut.actionString,"Cancel")
  XCTAssertEqual(action.mockTitle,"Cancel")
}

这个测试在此前的版本将会失败,因为初始化方法没有被调用,因此模拟标题也没有得到设置。

你可以在 github 上找到修正的版本。

再次感谢 Larhythimx 的推特!

本文由 SwiftGG 翻译组翻译,已经获得作者翻译授权,最新文章请访问 http://swift.gg

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...