Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to get a reference for Actionbar items for Junit testing in android?

How do I write junit test cases for actionbar items in android ? Any way of getting its reference for performing click events on it ?

like image 721
Pritam Avatar asked Jan 11 '12 17:01

Pritam


3 Answers

You can simulate clicking an ActionBar item like this:

public void testButton(){
    final View view = activity.findViewById(com.example.R.id.button1);
    activity.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            view.requestFocus();
            view.callOnClick();
        }
    });
}
like image 113
Xample Avatar answered Sep 21 '22 10:09

Xample


In this following example, i'm able to retrieve the navigation tab button of the action bar (native or ActionBarSherlock). Then i click on them with TouchUtils.clickView():

try {

// Trying to get the ActionBar view '@id/android:action_bar_container' dynamically
int resId =
a.getResources().getIdentifier("action_bar_container", "id", "android");
View actionBarContainer = a.findViewById(resId);

// The class 'com.android.internal.widget.ActionBarContainer' must be in
// the classpath of this test project to be able to call
// the method 'getTabContainer' at runtime
Method getTabContainer =
com.android.internal.widget.ActionBarContainer.class.getMethod("getTabContainer",
(Class<?>[]) null);

HorizontalScrollView tabContainer =
(HorizontalScrollView) getTabContainer.invoke(actionBarContainer, (Object[]) null);
return ((ViewGroup) tabContainer.getChildAt(0)).getChildAt(tabIndex);

} catch (Exception e) {

// Trying with SherlockActionBar
com.actionbarsherlock.internal.widget.ActionBarContainer actionBarContainer =
(com.actionbarsherlock...) a.findViewById(R.id.abs__action_bar_container);

HorizontalScrollView tabContainer =
(HorizontalScrollView) actionBarContainer.getTabContainer();
return ((ViewGroup) tabContainer.getChildAt(0)).getChildAt(tabIndex);

}
}
like image 30
Yann Avatar answered Sep 22 '22 10:09

Yann


use robotium.jar library

import com.jayway.android.robotium.solo.Solo;

private Solo solo;
this.solo = new Solo(getInstrumentation(),getActivity());
//R.id.menu_action_signup Menu Iten id.
this.solo.clickOnView(this.solo.getView(R.id.menu_action_signup));
like image 24
Satyam Raikar Avatar answered Sep 18 '22 10:09

Satyam Raikar