Espresso onData Error performing 'load adapter

2019-04-10 18:14发布

问题:

I have an app, have ListView, I want to find LinearLayout, id=order_untake_jijia_listview_jia

code is :

onData(withClassName(endsWith("ListView")))
            .inAdapterView(allOf(withId(R.id.order_untake_jijia_listview_ll), hasSibling(withText("9.0"))))
            .atPosition(0).onChildView(withId(R.id.order_untake_jijia_listview_jia));
            dataInteraction.perform(ViewActions.click());

But I have the error:

Error performing 'load adapter data' on view '(with id: com.edaixi:id/order_untake_jijia_listview_ll and has sibling: with text: is "9.0")'.
Caused by: java.lang.RuntimeException: Action will not be performed because the target view does not match one or more of the following constraints:
(is assignable from class: class android.widget.AdapterView and is displayed on the screen to the user)
Target view: "LinearLayout{id=2131493753, res-name=order_untake_jijia_listview_ll, visibility=VISIBLE, width=170, height=50, has-focus=false, has-focusable=false, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=572.0, y=25.0, child-count=3}"

回答1:

You are using onData incorrectly. onData takes an object matcher - it's intended to match the custom model object that is used to populate the list. So if you had a list of simple Strings, you would say onData(instanceOf(String.class)).atPosition(0) or onData(is("This exact String at position 0")).

inAdapterView is used to match the specific adapter view instance that contains your data. You need this when you have multiple lists on the screen you need to distinguish against. For example, if you had one ListView named R.id.list1 and a second R.id.list2 both containing Strings, you would say onData(is("The String")).inAdapterView(withId(R.id.list1)) to match the object in the first list.

You also generally do not need to specify a child view in these cases if you just need to click a single item in the adapter. You generally use onChildView to do an assertion on a child view item, or if you happen to have a separate dedicated click listener on that sub-view.

Thus, it seems as though you've overcomplicated the situation and you should be able to update your code to something like this:

onData(instanceOf(MyCustomClassOfObjectsInAdapter.java))
    .atPosition(0)
    .perform(click());

If that doesn't solve your problem, please provide some layout code of what your list items look like as well as the main screen layout that has the listview, and a screenshot with an example of the display and clarify what you're trying to match / act / assert against and I can try to guide you to the correct set of methods you need to accomplish what you need.

Hope that helps!