使用withId匹配器时Espresso NoMatchingViewException [英] Espresso NoMatchingViewException when using withId matcher

查看:388
本文介绍了使用withId匹配器时Espresso NoMatchingViewException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个简单的测试,只需单击主活动中的MenuItem即可.

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());
  }

}

测试失败,并显示"NoMatchingViewException".如果我将onView行更改为:

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

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

这是活动的菜单xml:

Here is the menu xml for the activity:

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

测试有效.为什么匹配项withText找不到视图,而匹配项withId找不到?

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

推荐答案

是的,这就是它在Espresso中的工作方式.这里的问题是,在Android中,代表菜单项的View没有菜单项的ID.因此onView(withId(X))只是找不到视图.除了使用withText()之外,我没有更好的建议.如果您有多个具有相同文本的视图,请使用层次结构进行区分.

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.

这篇关于使用withId匹配器时Espresso NoMatchingViewException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆