Is it possible to test IBAction?

后端 未结 7 835
深忆病人
深忆病人 2021-01-05 13:50

It is kinda easy to unit test IBOutlets, but how about IBActions? I was trying to find a way how to do it, but without any luck. Is there any way to unit test connection bet

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-05 14:12

    @AbbeyJackson Swift 3 version updated to Swift 4.2, thanks to @JulioBailon for the original version.

     func checkActionForButton(_ button: UIButton?, actionName: String, event: UIControl.Event = UIControl.Event.touchUpInside, target: UIViewController) -> Bool {
            if let unwrappedButton = button, let actions = unwrappedButton.actions(forTarget: target, forControlEvent: event) {
                var testAction = actionName
                if let trimmedActionName = actionName.components(separatedBy: ":").first {
                    testAction = trimmedActionName
                }
                return (!actions.filter { $0.contains(testAction) }.isEmpty)
            }
            return false
        }
    

提交回复
热议问题