How can I emulate clicking a button in my application test. I tried to set focus on the button and send the keypress "Enter" but no cigar.
4 Answers
Just call the performClick() method. See the View docs for reference.
Button button = (Button) findViewByid(R.id.mybutton);
button.performClick();
Or, if developing for Ice Cream Sandwich (API Level 15), the callOnClick() method was added. performClick() is more than suitable for your needs, though.
Comments
The accepted answer didn't quite work for me, the thing I was working with didn't have a performClick method. For future people who come here with a situation like mine where you're doing instrumented testing, you might need something like this:
onView(withId(R.id.myButton)).perform(ViewActions.click());
1 Comment
I had a lot of problems with the performClick method (relating to using the wrong thread and whatnot). I had a lot more luck with using TouchUtils.clickView as outlined in this android training lesson. Here is some sample usage:
public class ClickFunActivityTest extends ActivityInstrumentationTestCase2 {
...
@Override
protected void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(true);
mClickFunActivity = getActivity();
mClickMeButton = (Button)
mClickFunActivity.findViewById(R.id.launch_next_activity_button);
}
public void testClickMeButton_clickButtonAndExpectInfoText() {
TouchUtils.clickView(this, mClickMeButton);
//Do some other testing afterward
}
}
The complete code can be found in the link or here.