Issue
I want to write a unit test that verifies the number of users listed in a merge adapter.
My MergeAdapter list view has three elements:
- a header with some buttons,
- an adapter for the users,
- a footer with some buttons.
I've already found this code to check the number of children in a listview:
class Matchers {
public static Matcher<View> withListSize (final int size) {
return new TypeSafeMatcher<View>() {
@Override public boolean matchesSafely (final View view) {
return ((ListView) view).getChildCount () == size;
}
@Override public void describeTo (final Description description) {
description.appendText ("ListView should have " + size + " items");
}
};
}
}
but it always returns 3 because there are 3 sections in the `ListView.
I just want to check on the middle section which contains a user list.
This is my espresso code:
onView (withId (android.R.id.list)).check (ViewAssertions.matches(Matchers.withListSize(2)));
it should check if there are 2 users on the list, but this check fails as it returns 3 again (as I said before there are sections).
Here's a link to MergeAdapter: https://github.com/commonsguy/cwac-merge
Solution
as you said the test returns actually 3, because it catches the parent view, which has as you said three sections.
You need to add an additional matcher to get second element.
Take a look at in Java library included Hamcrest matchers reference: http://www.marcphilipp.de/downloads/posts/2013-01-02-hamcrest-quick-reference/Hamcrest-1.3.pdf
You may need to use withParent, withChild, hasSibling, hasDescendant matchers. So after that, your code may look like this:
onView(withParent(withId(android.R.id.list))).check(ViewAssertions.matches(Matchers.withListSize(2)));
I'm not sure, but if you're already using any kind of adapter, you may use onData instead of onView Espresso ViewMatcher.
You would find some useful information here: https://realm.io/news/chiu-ki-chan-advanced-android-espresso-testing
Hope it help
Answered By - piotrek1543
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.