I'm writing some unit tests and, because of the nature of this particular app, it's important that I get as high up the UI
chain as possible. So, what I'd like to do is programmatically trigger a button-press, as if the user had pressed the button in the GUI
.
(Yes, yes -- I could just call the IBAction
selector but, again, the nature of this particular app makes it important that I fake the actual button press, such that the IBAction
be called from the button, itself.)
What's the preferred method of doing this?
For Xamarin iOS
Reference
It turns out that
got me exactly what I needed, in this case.
EDIT: Don't forget to do this in the main thread, to get results similar to a user-press.
For Swift 3:
buttonObj.sendActions(for: .touchUpInside)
If you want to do this kind of testing, you’ll love the UI Automation support in iOS 4. You can write JavaScript to simulate button presses, etc. fairly easily, though the documentation (especially the getting-started part) is a bit sparse.
An update to this answer for Swift
EDIT: Updated for Swift 3
In this case,
UIButton
is derived fromUIControl
. This works for object derived fromUIControl
.I wanted to reuse "
UIBarButtonItem
" action on specific use case. Here,UIBarButtonItem
doesn't offer methodsendActionsForControlEvents:
But luckily,
UIBarButtonItem
has properties for target & action.Here,
rightBarButtonItem
is of typeUIBarButtonItem
.Swift 3: