How to click on an index in the options menu using Espresso Android

I call up the options menu using this code:
openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext());

After that, a menu appeared. Now I click on the menu item according to its text, and this is normal.

The problem that I have already noticed is a subject that can change, say, if a user uses many languages ​​for different clients. So in a long test run this is not useful.

For this reason, I want to use Espresso to click on a specific index for a specific test case.

There is no identifier in the settings menu. So I don’t know how to click on a specific β€œindex” element in this menu, say, I want to click on the fourth element.

Could you help me solve it?

+6
source share
2 answers

So, I would try to explain this step by step:

1) You opened the menu in this way:

 openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext()); 

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

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

2) You want to click an item by ID:

First, why don't you use "strings.xml". The text extracted from this file is automatically changed using the language of the set of smartphones, but only if you prepared it before the exact translation file.

What the code will look like:

 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 will still catch the view by its identifier, as @Rodrigo said. What the code will look like:

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

Remember that in your xml files you can declare android:id , android:text or android:contentDescription for each "view".

+4
source

I just selected a menu item based on its identifier.

 onView(withId(R.id.some_option_menu_id)).perform(click()); 
0
source

All Articles