簡體   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