繁体   English   中英

在浓缩咖啡中获取RecyclerView总项目数

[英]Get RecyclerView total item count in espresso

我正在使用RecyclerView,我需要使用android espresso获取RecyclerView中的项目总数。 我该怎么做 ?

我会这样做:

@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();
}

虽然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)));
}

以下是RecyclerViewItemCountAssertion类的代码(只需将其放在单独的文件中)。 注意有两个构造函数可用:

  1. RecyclerViewItemCountAssertion(int expectedCount) -整型参数的预期,默认is匹配时使用。
  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM