Skip to content

Instantly share code, notes, and snippets.

@kowalcj0
Last active September 5, 2016 11:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kowalcj0/a9ea58c0b89e723e44b54023726fb4ba to your computer and use it in GitHub Desktop.
Save kowalcj0/a9ea58c0b89e723e44b54023726fb4ba to your computer and use it in GitHub Desktop.
A Kotlin implementation of the RecycleViewMatcher for Espresso
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;
/**
* @author https://github.com/ebelli
**/
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)",
new Object[] { Integer.valueOf
(recyclerViewId) });
}
}
description.appendText("with id: " + idDescription);
}
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) {
childView = recyclerView.getChildAt(position);
}
else {
return false;
}
}
if (targetViewId == -1) {
return view == childView;
} else {
View targetView = childView.findViewById(targetViewId);
return view == targetView;
}
}
};
}
public static RecyclerViewMatcher withRecyclerView(final int recyclerViewId) {
return new RecyclerViewMatcher(recyclerViewId);
}
}
@kowalcj0
Copy link
Author

kowalcj0 commented Sep 5, 2016

Example usage:

val rv : RecyclerViewMatcher = RecyclerViewMatcher.withRecyclerView(R.id.some_RV_ID)
onView(rv.atPositionOnView(position, R.id.some_view_id)).check(matches(isDisplayed()))

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