Skip to content

Instantly share code, notes, and snippets.

@takahirom
Forked from baconpat/RecycleViewMatcher.java
Created June 3, 2017 08:23
Show Gist options
  • Save takahirom/8fb086510cf8aca211ff5f14a1ffa7ff to your computer and use it in GitHub Desktop.
Save takahirom/8fb086510cf8aca211ff5f14a1ffa7ff to your computer and use it in GitHub Desktop.
RecycleViewMatcher (updated for scrolling)
package com.foo.RecyclerViewMatcher;
import android.content.res.Resources;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
/**
* Fork of the RecyclerViewMatcher from https://github.com/dannyroa/espresso-samples
*/
public class RecyclerViewMatcher {
private final int recyclerViewId;
public RecyclerViewMatcher(int recyclerViewId) {
this.recyclerViewId = recyclerViewId;
}
public Matcher<View> atPosition(final int position) {
return atPositionOnView(position, -1);
}
public Matcher<View> atPositionOnView(final int position, final int targetViewId) {
return new TypeSafeMatcher<View>() {
Resources resources = null;
View childView;
public void describeTo(Description description) {
String idDescription = Integer.toString(recyclerViewId);
if (this.resources != null) {
try {
idDescription = this.resources.getResourceName(recyclerViewId);
} catch (Resources.NotFoundException var4) {
idDescription = String.format("%s (resource name not found)", recyclerViewId);
}
}
description.appendText("RecyclerView with id: " + idDescription + " at position: " + position);
}
public boolean matchesSafely(View view) {
this.resources = view.getResources();
if (childView == null) {
RecyclerView recyclerView =
(RecyclerView) view.getRootView().findViewById(recyclerViewId);
if (recyclerView != null && recyclerView.getId() == recyclerViewId) {
RecyclerView.ViewHolder viewHolder = recyclerView.findViewHolderForAdapterPosition(position);
if (viewHolder != null) {
childView = viewHolder.itemView;
}
}
else {
return false;
}
}
if (targetViewId == -1) {
return view == childView;
} else {
View targetView = childView.findViewById(targetViewId);
return view == targetView;
}
}
};
}
}
@takahirom
Copy link
Author

takahirom commented Jun 3, 2017

https://gist.github.com/baconpat/8405a88d04bd1942eb5e430d33e4faa2

FYR:

            onView(new RecyclerViewMatcher(R.id.repo_list).atPosition(pos)).check(
                    matches(hasDescendant(withText(repo.name))));
            onView(new RecyclerViewMatcher(R.id.repo_list).atPosition(pos)).check(
                    matches(hasDescendant(withText(repo.description))));
            onView(new RecyclerViewMatcher(R.id.repo_list).atPosition(pos)).check(
                    matches(hasDescendant(withText("" + repo.stars))));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment