获取espresso中的商品

时间:2017-09-19 15:40:48

标签: android menuitem android-espresso

我是Espresso的初学者。我有这个menu.xml文件:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/configuration"
        android:icon="@drawable/ic_settings"
        android:title="Configuration"
        app:showAsAction="ifRoom">

        <menu>
            <item
                android:id="@+id/add_sound"
                android:title="Add a sound"
                app:showAsAction="ifRoom" />

            <item
                android:id="@+id/takeof_sound"
                android:enabled="false"
                android:title="Take of the sound"
                app:showAsAction="ifRoom" />

            <item
                android:id="@+id/add_image"
                android:title="Add an image"
                app:showAsAction="ifRoom" />

            <item
                android:id="@+id/takeof_image"
                android:enabled="false"
                android:title="Take of the image"
                app:showAsAction="ifRoom" />
        </menu>

    </item>

    <item
        android:id="@+id/add"
        android:icon="@drawable/ic_add"
        android:title="Add"
        app:showAsAction="ifRoom" />
</menu>

我想点击标识为configuration的项目,然后点击标识为add_sound的子项目。所以,我输入了这段代码:

public void menuConfigurationTest()
    {
        onView(withId(R.id.configuration)).perform(click());
        onView(withId(R.id.add_sound)).perform(click());
    }

但是我收到了这个错误:

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with id: com.example.adrien.smartalarm:id/add_sound
If the target view is not part of the view hierarchy, you may need to use Espresso.onData to load it from one of the following AdapterViews:android.support.v7.widget.MenuPopupWindow$MenuDropDownListView{5a0c4d8 VFED.VC.. .F...... 0,0-686,672}

我做了什么错了?

1 个答案:

答案 0 :(得分:1)

问题是子菜单显示在PopupWindow中,而PopupWindow不是活动视图层次结构的一部分。因此,您必须添加:

.inRoot(RootMatchers.isPlatformPopup())

接下来的事情是项目显示在一个名为MenuDropDownListView的特殊ListView中。所以onView()在这里不起作用,你必须使用onData()。

因此完整的表达是:

onData(CoreMatchers.anything())
        .inRoot(RootMatchers.isPlatformPopup()) // isPlatformPopup() == is in PopupWindow
        .inAdapterView(CoreMatchers.<View>instanceOf(MenuPopupWindow.MenuDropDownListView.class))
        .atPosition(0) // for the first submenu item, here: add_sound
        .perform(click());