Skip to content

Instantly share code, notes, and snippets.

@akihito104
Last active September 17, 2017 04:09
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 akihito104/514a8a96ed4c6504683ab750a5d71c1d to your computer and use it in GitHub Desktop.
Save akihito104/514a8a96ed4c6504683ab750a5d71c1d to your computer and use it in GitHub Desktop.
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

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