[英]Get RecyclerView total item count in espresso
I am using RecyclerView and i need to get the total count of items in the RecyclerView using android espresso. 我正在使用RecyclerView,我需要使用android espresso获取RecyclerView中的项目总数。 How can i do it ?
我该怎么做 ?
I would do it like this: 我会这样做:
@Rule
public ActivityTestRule<MyClass> activityRule = new ActivityTestRule(MyActivity.class);
@Test
public void myTest() {
RecyclerView recyclerView = activityRule.getActivity().findViewById(R.id.my_recyclerview)
int itemCount = recyclerView.getAdapter().getItemCount();
}
While Thekarlo95's answer specifically and fully answers the question, I would like to show my example on how to use his method together with Stéphane's method to test a difference in count before and after specific action: 虽然Thekarlo95的答案明确并完全回答了这个问题,但我想展示一下如何使用他的方法和Stéphane的方法来测试特定动作之前和之后的计数差异:
@Test
public void FilterClickShouldChangeRecyclerViewCount() {
// Get items count before action
RecyclerView recyclerView = mActivityTestRule.getActivity().findViewById(R.id.recycler_view);
int countBefore = Objects.requireNonNull(recyclerView.getAdapter()).getItemCount();
Log.e("count", "Items count before: " + countBefore);
// Perform action
ViewInteraction actionMenuItemView = onView(
allOf(
withId(R.id.action_filter),
withContentDescription("Show Favorites")));
actionMenuItemView.perform(click());
// Verify that items count has changed
onView(withId(R.id.recycler_view))
// Instead of 'not', you can use any other hamcrest Matcher like 'is', 'lessThan' etc.
.check(new RecyclerViewItemCountAssertion(not(countBefore)));
}
And below is a code for RecyclerViewItemCountAssertion
class (just put it on a separate file). 以下是
RecyclerViewItemCountAssertion
类的代码(只需将其放在单独的文件中)。 Note there are two constructors available: 注意有两个构造函数可用:
RecyclerViewItemCountAssertion(int expectedCount)
- parameter of type integer is expected, default is
matcher is used. RecyclerViewItemCountAssertion(int expectedCount)
-整型参数的预期,默认is
匹配时使用。 RecyclerViewItemCountAssertion(Matcher<Integer> matcher)
- parameter of type Matcher<Integer>
is expected, like is(3)
, lessThan(4)
etc. RecyclerViewItemCountAssertion(Matcher<Integer> matcher)
- 期望类型为Matcher<Integer>
参数,如is(3)
, lessThan(4)
等。
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(); assert adapter != null; assertThat(adapter.getItemCount(), matcher); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.