I want to get a reference to a MenuItem from the ActionBar of an activity for unit testing purpose.

@Override
protected void setUp() throws Exception{
    super.setUp();
    viewContacts = getActivity();

    addContactsBtn = (MenuItem)viewContacts.findViewById(R.id.action_add);
    searchBtn = (MenuItem)viewContacts.findViewById(R.id.action_search);

}

where, action_add and action_search are defined in my menu.xml file as follows

<item
    android:id="@+id/action_search"
    android:orderInCategory="0"
    android:showAsAction="always"
    android:icon="@drawable/ic_action_search"
    android:title="@string/action_search"/>
<item 
    android:id="@+id/action_add"
    android:orderInCategory="1"
    android:showAsAction="always"
    android:icon="@drawable/ic_action_add"
    android:title="@string/action_add"/>

The test case throws ClassCastException-

java.lang.ClassCastException: com.android.internal.view.menu.ActionMenuItemView cannot be cast to android.view.MenuItem at com.example.simplecontacts.test.ViewContactsTest.setUp(ViewContactsTest.java:24) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:190) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:175) at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1661)

I researched ways to obtain a reference to a MenuItem. Usual way to do this is via the Menu/MenuItem arguments passed into the onOptionsItemSelected, onPrepareOptionsMenu methods. That is perfectly logical in the application project itself but how should I obtain MenuItem reference inside the test project?

有帮助吗?

解决方案

Well, it turns out that casting them into View objects is sufficient for unit testing purpose. So the code will be like so

addContactsBtn = (View)viewContacts.findViewById(R.id.action_add);
searchBtn = (View)viewContacts.findViewById(R.id.action_search);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top