2

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 4

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Just to mention for clarity, this code is useful if you are using Espresso library
0

Please look at Robotium project. It is a test framework for Android and you can achieve what you desire easily with it, and much more.

1 Comment

for now I'd prefer to stay within the confines of the standard Android testing framework
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.