How can you test the contents of a UIAlertAction handler with OCMock

后端 未结 2 1674
天涯浪人
天涯浪人 2021-01-14 03:28

I\'ve got an app where I push a UIAlertController with several custom UIAlertActions. Each UIAlertAction performs unique tasks in the

2条回答
  •  天涯浪人
    2021-01-14 04:21

    With a bit of clever casting, I've found a way to do this in Swift (2.2):

    extension UIAlertController {
    
        typealias AlertHandler = @convention(block) (UIAlertAction) -> Void
    
        func tapButtonAtIndex(index: Int) {
            let block = actions[index].valueForKey("handler")
            let handler = unsafeBitCast(block, AlertHandler.self)
    
            handler(actions[index])
        }
    
    }
    

    This allows you to call alert.tapButtonAtIndex(1) in your test and have the correct handler executed.

    (I would only use this in my test target, btw)

提交回复
热议问题