Reputation: 17851
I have the following menu item that I want to click using Espresso:
<item
android:id="@+id/action_save"
android:icon="@drawable/vector_image_save"
android:orderInCategory="4"
android:title="@string/menu_action_save"
app:showAsAction="ifRoom"/>
Due to ifRoom
, in some devices the menu is shown as an icon in action bar while in smaller devices it's shown under the "more options".
I could use the below code to tap on the Save icon in the action bar:
onView(withId(R.id.action_save)).perform(click());
And I could use the below code to tap on Save if it's present under the "more options":
openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext());
onView(withText(R.string.menu_action_save)).perform(click());
I want a single test method that would work in both cases.
Upvotes: 3
Views: 2634
Reputation: 17851
try {
onView(withId(R.id.action_save)).perform(click());
} catch (NoMatchingViewException e) {
openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext());
onView(withText(R.string.menu_action_save)).perform(click());
}
You will first check if the menu is present as an icon. If so, click on it. If not, open up the "More options" menu and then select the "Save" menu from the popup.
Note: I know that we shouldn't use conditions in test methods, but I really couldn't find any other solution. If any of you do find a better solution, please post it here.
Upvotes: 8