Android Espresso - 无法单击从适配器生成的列表视图中的文本

时间:2017-07-17 02:26:04

标签: android listview text adapter android-espresso

目前我的活动有自动完整文字视图。文本视图中的数据是从数组适配器填充的,我在让测试用例按名称单击其中一个List View元素时遇到问题。这是截图和代码:

// setup ingredient list widget
    mFridgeList = (ListView) findViewById(R.id.fridge_list);
    mFridgeList.setAdapter(new ArrayAdapter<String>(this,
            android.R.layout.simple_dropdown_item_1line, FridgesterDB.ingredientsList));

enter image description here

当用户键入文本(例如:tom)时,将出现一个选项列表,然后用户可以选择这些选项以确认其选择。

我觉得我尝试了一千种不同的解决方案,但我得到的最一致的错误是:

在视图上执行'加载适配器数据'时出错'可从类中分配:class android.widget.AdapterView

我尝试使用建议的解决方案here

onData(hasToString(startsWith("tomato"))).perform(click());

并且它的不同变化无济于事。

这是从Espresso Recorder生成的代码,它会导致NoMatchingViewException:

ViewInteraction appCompatTextView = onView(
            allOf(withId(android.R.id.text1), withText("tomato"), isDisplayed()));
appCompatTextView2.perform(click());

NoMatchingViewException:层次结构中找不到匹配的视图:(带有id:android:id / text1,带有text:是“番茄”,并在屏幕上显示给用户)

我也看到过一些人通过使用睡眠来让这个工作起来,但这对我的情况没有任何影响。有任何想法吗?感谢

1 个答案:

答案 0 :(得分:0)

我能够使用此处建议的答案:Espresso AutoCompleteTextView click

onData(allOf(instanceOf(BaseIngredient.class), withContent(ingredient))).inRoot(RootMatchers.withDecorView(not(is(mActivityTestRule.getActivity().getWindow().getDecorView())))).perform(ViewActions.click());

我必须创建一个自定义匹配器,因为适配器中的每个元素都是 BaseIngredient 对象。

public static Matcher<Object> withContent(final String title) {
    return new BoundedMatcher<Object, BaseIngredient>(BaseIngredient.class) {
        @Override
        public boolean matchesSafely(BaseIngredient myObj) {
            return myObj.mName.equals(title);
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("with title '" + title + "'");
        }
    };
}