Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click on index on option menu using Espresso Android

I call on option menu using this code:
openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());

After that, the menu appeared. Now I click on the menu item by its text, and that is fine.

The problem that I already noticed is is subject, which can change, let's say if user uses many languages for different clients. So in the long test run it's not useful.

For that reason I want to use Espresso to click on specific index for specific test case.

The settings menu does not seems to have an ID. So I don't know how to click on specific item 'index' in that menu, let's say I want to click at fourth item.

Could you help me with solve it?

like image 679
Moody Avatar asked Jul 24 '15 06:07

Moody


2 Answers

So, I would try to explain it step after step:

1) You opened the menu by this method:

openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());

I think that you can open the same menu by putting this code:

onView(withContentDescription("More options")).perform(click());

2) You want to click on item by Id:

First, why don't you want to use 'strings.xml.' Text extracted from this file is changed automatically with smartphone set language, but only if you prepared before exact translation file.

Than the code would look like this:

openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());
onView(withText(R.string.help)).perform(click());

or

onView(withContentDescription("More options")).perform(click());
onView(withText(R.string.help)).perform(click());

Of course, you still do catch a view by its id, like @Rodrigo said. Than the code would be like this:

onView(withContentDescription("More options")).perform(click());
onView(withId(R.id.help_item)).perform(click());

Remember that in your xml files you can for every single 'view' declare android:id,android:text or android:contentDescription.

like image 139
piotrek1543 Avatar answered Sep 21 '22 13:09

piotrek1543


I just selected the menu item based on his ID.

onView(withId(R.id.some_option_menu_id)).perform(click());
like image 41
Rodrigo Henriques Avatar answered Sep 19 '22 13:09

Rodrigo Henriques