Search code examples
androidtestingmenujunitactionbarsherlock

How to test Android ActionBar submenus?


Do anyone have any idea how to test actionbar submenu items with the android testing framework? I'm using ActionBarSherlock. I don't have a problem with clicking the first menu item to get the drop down menu like so:

    final View deleteView = (View) activity.findViewById(R.id.action_discard_trans);
    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            deleteView.requestFocus();
        }
    });
    TouchUtils.clickView(TransListFragTest.this, deleteView);

But I get a null view when I try to get the submenu item after the drop down shows.

final View deleteMultiple = (View) activity.findViewById(R.id.am_delete_occurrences);
assertNotNull(deleteMultiple);

Here is my menu xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:com.paycheckplan="http://schemas.android.com/apk/res-auto" >

<item
    android:id="@+id/action_discard_trans"
    android:icon="@drawable/content_discard"
    android:showAsAction="always"
    android:title="@string/discard_trans">
    <menu>
        <item
            android:id="@+id/am_delete_one"
            android:title="@string/action_mode_delete_one"/>
        <item
            android:id="@+id/am_delete_occurrences"
            android:title="@string/action_mode_delete_occurrences"/>
    </menu>
</item>


Solution

  • I found that using solo.getView(R.id.am_delete_occurrences) is a lot more reliable than activity.findViewById(R.id.am_delete_occurrences). A common occurrence where the solo version works and the activity reference doesn't is when you do a configuration change or you are trying to find a view within a fragment that's in the activity.