我正在使用RecyclerView,我需要使用android espresso获取RecyclerView中的项目总数。我该怎么办?
答案 0 :(得分:3)
我会这样做:
@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();
}
答案 1 :(得分:0)
在Thekarlo95's answer具体而完整地回答问题的同时,我想展示我的示例,说明如何与Stéphane's method一起使用他的方法来测试特定动作前后的计数差异:>
@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
类的代码(只需将其放在单独的文件中)。请注意,有两个可用的构造函数:
RecyclerViewItemCountAssertion(int expectedCount)
-预期为整数类型的参数,使用默认的is
匹配器。 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);
}
}