android android-recyclerview android-espresso hamcrest

android - Cómo contar elementos RecyclerView con Espresso



android-recyclerview android-espresso (6)

Usando Espresso y Hamcrest,

¿Cómo puedo contar el número de artículos disponibles en un recyclerView?

Ejemplo: me gustaría comprobar si se muestran 5 elementos en un RecyclerView específico (desplazándose si es necesario).


Añadiendo un poco de azúcar sintáctica a la respuesta de @Stephane .

public class RecyclerViewItemCountAssertion implements ViewAssertion { private final Matcher<Integer> matcher; public static RecyclerViewItemCountAssertion withItemCount(int expectedCount) { return withItemCount(is(expectedCount)); } public static RecyclerViewItemCountAssertion withItemCount(Matcher<Integer> matcher) { return new RecyclerViewItemCountAssertion(matcher); } private RecyclerViewItemCountAssertion(Matcher<Integer> matcher) { this.matcher = matcher; } @Override public void check(View view, NoMatchingViewException noViewFoundException) { if (noViewFoundException != null) { throw noViewFoundException; } RecyclerView recyclerView = (RecyclerView) view; RecyclerView.Adapter adapter = recyclerView.getAdapter(); assertThat(adapter.getItemCount(), matcher); } }

Uso:

import static your.package.RecyclerViewItemCountAssertion.withItemCount; onView(withId(R.id.recyclerView)).check(withItemCount(5)); onView(withId(R.id.recyclerView)).check(withItemCount(greaterThan(5)); onView(withId(R.id.recyclerView)).check(withItemCount(lessThan(5)); // ...


Aquí un ejemplo de ViewAssertion para verificar el recuento de elementos de RecyclerView

public class RecyclerViewItemCountAssertion implements ViewAssertion { private final int expectedCount; public RecyclerViewItemCountAssertion(int expectedCount) { this.expectedCount = expectedCount; } @Override public void check(View view, NoMatchingViewException noViewFoundException) { if (noViewFoundException != null) { throw noViewFoundException; } RecyclerView recyclerView = (RecyclerView) view; RecyclerView.Adapter adapter = recyclerView.getAdapter(); assertThat(adapter.getItemCount(), is(expectedCount)); } }

y luego usa esta afirmación

onView(withId(R.id.recyclerView)).check(new RecyclerViewItemCountAssertion(5));

Empecé a escribir una biblioteca que debería hacer las pruebas más simples con espresso y uiautomator. Esto incluye herramientas para acciones y aserciones de RecyclerView. https://github.com/nenick/espresso-macchiato Vea por ejemplo EspRecyclerView con el método assertItemCountIs (int)


Basado en @Sivakumar Kamichetty respuesta:

  1. Se accede a la variable ''COUNT'' desde dentro de la clase interna, necesita ser declarada final.
  2. Línea innecesariamente: COUNT = 0;
  3. Transfiere la variable COUNT a una matriz de elementos.
  4. El result variable es innecesario.

No es lindo, pero funciona:

public static int getCountFromRecyclerView(@IdRes int RecyclerViewId) { final int[] COUNT = {0}; Matcher matcher = new TypeSafeMatcher<View>() { @Override protected boolean matchesSafely(View item) { COUNT[0] = ((RecyclerView) item).getAdapter().getItemCount(); return true; } @Override public void describeTo(Description description) {} }; onView(allOf(withId(RecyclerViewId),isDisplayed())).check(matches(matcher)); return COUNT[0]; }


Para completar la respuesta nenick y proporcionar una solución un poco más flexible para probar también si el elemento cout es mayor que, menos que ...

public class RecyclerViewItemCountAssertion implements ViewAssertion { private final Matcher<Integer> matcher; public RecyclerViewItemCountAssertion(int expectedCount) { this.matcher = is(expectedCount); } public RecyclerViewItemCountAssertion(Matcher<Integer> matcher) { this.matcher = matcher; } @Override public void check(View view, NoMatchingViewException noViewFoundException) { if (noViewFoundException != null) { throw noViewFoundException; } RecyclerView recyclerView = (RecyclerView) view; RecyclerView.Adapter adapter = recyclerView.getAdapter(); assertThat(adapter.getItemCount(), matcher); } }

Uso:

onView(withId(R.id.recyclerView)).check(new RecyclerViewItemCountAssertion(5)); onView(withId(R.id.recyclerView)).check(new RecyclerViewItemCountAssertion(greaterThan(5)); onView(withId(R.id.recyclerView)).check(new RecyclerViewItemCountAssertion(lessThan(5)); // ...


Puede crear un BoundedMatcher personalizado:

object RecyclerViewMatchers { @JvmStatic fun hasItemCount(itemCount: Int): Matcher<View> { return object : BoundedMatcher<View, RecyclerView>( RecyclerView::class.java) { override fun describeTo(description: Description) { description.appendText("has $itemCount items") } override fun matchesSafely(view: RecyclerView): Boolean { return view.adapter.itemCount == itemCount } } } }

Y luego úsalo así:

onView(withId(R.id.recycler_view)).check(matches((hasItemCount(5))))


Utilicé el siguiente método para obtener el recuento de RecyclerView

public static int getCountFromRecyclerView(@IdRes int RecyclerViewId) { int COUNT = 0; Matcher matcher = new TypeSafeMatcher<View>() { @Override protected boolean matchesSafely(View item) { COUNT = ((RecyclerView) item).getAdapter().getItemCount(); return true; } @Override public void describeTo(Description description) { } }; onView(allOf(withId(RecyclerViewId),isDisplayed())).check(matches(matcher)); int result = COUNT; COUNT = 0; return result; }

Uso -

int itemsCount = getCountFromRecyclerView(R.id.RecyclerViewId);

A continuación, realice las afirmaciones para verificar si el objeto itemsCount es el esperado