使用withId匹配器时,Espresso出现NoMatchingViewException异常。

9
我正在尝试编写一个简单的测试,只需点击位于主活动中的菜单项:
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());
  }

}

测试失败并出现“ NoMatchingViewException ”。如果我将onView行更改为:
    onView(withText("Add new")).perform(ViewActions.click());

以下是该活动的菜单XML:

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

测试通过了。为什么使用withText匹配器可以找到视图,而使用withId匹配器却找不到呢?
2个回答

15

是的,在Espresso中就是这样运作的。问题在于,Android中代表菜单项的View没有菜单项的ID。因此,onView(withId(X))无法找到View。我没有比使用withText()更好的建议。如果您有多个具有相同文本的视图,则可以使用层次结构进行区分。


请你帮忙查看下面的问题,麻烦你看一下,非常感谢。https://stackoverflow.com/questions/76472775/navigation-view-android-kotlin-with-espresso-androidx-test-espresso-nomatching - Naveen

3

haffax的答案是正确的。菜单项和为菜单生成的视图具有不同的ID。在这种情况下,使用withText是最好的实践方法。

为了避免在测试中硬编码文本,我建议使用字符串引用。例如,

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接