Skip to content

Instantly share code, notes, and snippets.

@paulz
Last active February 6, 2024 09:49
Show Gist options
  • Save paulz/91af10b2655d4b9d1ac34495e2ab357d to your computer and use it in GitHub Desktop.
Save paulz/91af10b2655d4b9d1ac34495e2ab357d to your computer and use it in GitHub Desktop.
Make UIAction handler accessible for testing
import Quick
import Nimble
class ActionSpec: QuickSpec {
override func spec() {
describe("UIAction") {
it("should invoke handler") {
waitUntil { done in
let action = UIAction(title: "a title") { action in
done()
}
action.handler(action)
}
}
}
}
}
import XCTest
class ActionTest: XCTestCase {
func testActionHandler() {
var handlerWasCalled = false
let action = UIAction(title: "a title") { action in
handlerWasCalled = true
}
action.handler(action)
XCTAssertTrue(handlerWasCalled, "should be called")
}
}
import UIKit
extension UIAction {
var handler: UIActionHandler {
get {
typealias ActionHandlerBlock = @convention(block) (UIAction) -> Void
let handler = value(forKey: "handler") as AnyObject
return unsafeBitCast(handler, to: ActionHandlerBlock.self)
}
}
}
@oconnelltoby
Copy link

Shame it's hidden in the first place!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment