2017-08-15 24 views
0

我可以用视图操作来执行对个别列表项如何透过Espresso

onView(withId(R.id.rv_recycler_view)) 
       .perform(actionOnItemAtPosition(0, click())); 

不过,我想返回的列表项目的数目点击得到回收视图列表项目计数,并使用循环点击在每个列表项目上,而不用为每个项目编写单独的代码片段。

如何返回回收商视图包含的清单物品数量?也许我需要直接通过活动访问适配器变量?

感谢

回答

0

我会踩灭的依赖关系,如果你在3项养活你可以控制你的测试环境,即,你应该预料到会显示三个项目。您可以通过nenick与自定义操作检查这个How to count RecyclerView items with Espresso

public class CustomRecyclerViewAssertions { 
//Asserts the number of items in a RecyclerView 

    public static ViewAssertion AssertItemCount(final int expectedCount) { 
    return new ViewAssertion() { 
     @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)); 
     } 
    }; 
    } 
} 

这是通过使用

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

一旦你知道有多少项目都存在调用,您可以使用:

onView(withId(R.id.recyclerView)).perform(
     actionOnItemAtPosition<RecyclerView.ViewHolder>(1, click())) 

由于recyclerView显示同一视图的多个实例,因此我不会浪费时间复制代码来单击每个项目

+0

看起来过于复杂,而且我没有断言一个数字,我正在查看一个数字。为什么我不能调用'adapter.getItemCount()'并使用循环来使用循环索引点击每个项目? –