Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Espresso for RecyclerView

custom matcher and assertion

  private Matcher<View> ofMyCustomView(Matcher<View> matcher) {
    return new BoundedMatcher<View, MyCustomView>(MyCustomView.class) {
      @Override
      protected boolean matchesSafely(MyCustomView item) {
        final Iterable<View> it = Iterables.filter(TreeIterables.breadthFirstViewTraversal(item),
            new Predicate<View>() {
              @Override
              public boolean apply(@Nullable View view) {
                return view != null
                    && matcher.matches(view);
              }
            });
        return it.iterator().hasNext();
      }

      @Override
      public void describeTo(Description description) {
        viewMatcher.describeTo(description);
      }
    };
  }

  private ViewAssertion recyclerViewDescendantsMatches(
      @IdRes final int recyclerViewId, final int position) {
    return new ViewAssertion() {
      @Override
      public void check(View view, NoMatchingViewException noViewFoundException) {
        if (!(view instanceof MyCustomView)) {
          throw noViewFoundException;
        }
        final RecyclerView recyclerView = (RecyclerView) view.getParent();
        if (recyclerView == null
            || recyclerView.getId() != recyclerViewId) {
          throw noViewFoundException;
        }
        final View actual = recyclerView.getChildAt(position);
        if (view != actual) {
          throw noViewFoundException;
        }
      }
    };
  }

usage

onView(ofMyCustomView(withText("hoge")))
  .check(recyclerViewDescendantsMatches(R.id.recycler_view, 0));
@akihito104
Copy link
Author

akihito104 commented Sep 17, 2017

android.support.test.espresso.core.deps.guava.collect.Iterables is not in Espresso 3+.

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