This is how I unit test tap gesture recognizer in Swift. The test makes sure the code that responds to the tap gesture is executed.
First, I create an OnTap helper class
class OnTap: NSObject {
var closure: ()->()
init(view: UIView, gesture: UIGestureRecognizer, closure:() -> ()) {
self.closure = closure
super.init()
view.userInteractionEnabled = true
view.addGestureRecognizer(gesture)
gesture.addTarget(self, action: "didTap:")
}
func didTap(gesture: UIGestureRecognizer) {
closure()
}
}
Next, I register a tap gesture wit a view and a callback closure
class MyClass {
var onTap: OnTap?
var didTap = false
func setupTap() {
let myView = UIView()
onTap = OnTap(view: myView, gesture: UITapGestureRecognizer()) { [weak self] in
self?.didTap = true
}
}
}
Finally, I simulate the tap in my unit test and check that the closure has been called
class MyGestureTests: XCTestCase {
func testRepondToGesture() {
let obj = MyClass()
obj.setupTap()
obj.onTap?.didTap(UITapGestureRecognizer())
XCTAssert(obj.didTap)
}
}
Note, this is a unit testing technique. In addition, I use UI tests to make sure all pieces work together in sweet harmony.