9

I'm trying to write a simple test where I simply click on a MenuItem that is in the main activity:

public class doTest extends ActivityInstrumentationTestCase2<doActivity> {

  public doTest() {
    super(doActivity.class);
  }

  @Override
  public void setUp() throws Exception {
    super.setUp();
    startActivity();

  }

  private void startActivity() {
    Intent intent = new Intent();
    setActivityIntent(intent);
    getActivity();
  }

  public void testOne() {
    Espresso.openContextualActionModeOverflowMenu();
    onView(withId(R.id.create_new)).perform(ViewActions.click());
  }

}

The test fails with "NoMatchingViewException". If I change the onView line to:

    onView(withText("Add new")).perform(ViewActions.click());

Here is the menu xml for the activity:

 <item
        android:id="@+id/create_new"
        android:title="Add new"
        tools:ignore="HardcodedText">
    </item>

The test works. Why would the matcher withText find the view whereas the matcher withId not find?

Omar
  • 7,835
  • 14
  • 62
  • 108

2 Answers2

15

Yes, this is how it works in Espresso. The problem here is, that in Android, the View representing the menu item doesn't have the ID of the menu item. So onView(withId(X)) just fails to find a View. I don't have a better recommendation than just using withText(). If you have multiple views with the same text, using hierarchy for distinction works.

haffax
  • 5,898
  • 1
  • 32
  • 30
  • Could you please check on the below question, Could you please on this, Thanks in Advance. https://stackoverflow.com/questions/76472775/navigation-view-android-kotlin-with-espresso-androidx-test-espresso-nomatching – Naveen Jun 19 '23 at 11:21
3

haffax's answer is right. The menu item and the View generated for the menu have different IDs. Using withText is the best known practice in this case.

To avoid hardcoding a text like 'Add new' in your test, I would recommmand using a String reference. E.g.,

<item
    android:id="@+id/create_new"
    android:title="@string/action_create_new"
    tools:ignore="HardcodedText"
/>
lacton
  • 2,316
  • 2
  • 22
  • 24