我仍然在努力提高我对接收器的扩展功能的理解,并且需要一些专家的帮助来解决我对此的疑问。
我有一个Android Espresso测试用例,我检查我是否选择了recyclerview的项目。这是重复多次的相同代码。我想知道是否可以使用带接收器的kotlins扩展功能来简化这一过程。
我现在的测试代码:
@Test
public void shouldSelectAll() {
...
onView(withRecyclerView(R.id.multiselectview_recycler_view).atPosition(0))
.check(RecyclerViewMatcher.isSelected(true));
onView(withRecyclerView(R.id.multiselectview_recycler_view).atPosition(1))
.check(RecyclerViewMatcher.isSelected(true));
onView(withRecyclerView(R.id.multiselectview_recycler_view).atPosition(2))
.check(RecyclerViewMatcher.isSelected(true));
}
是否有可能创建一个函数 atPositions(varag positions: Int)
,它将采用整数数组并在数组中的每个位置调用断言。像这样:
@Test
public void shouldSelectAll() {
...
onView(withRecyclerView(R.id.multiselectview_recycler_view).atPositions(0, 1, 2))
.check(RecyclerViewMatcher.isSelected(true));
}
答案 0 :(得分:2)
当然!
private fun Int.matchAsRecyclerView(): RecyclerViewMatcher = withRecyclerView(this)
private fun RecyclerViewMatcher.checkAtPositions(vararg indices: Int, assertionForIndex: (Int) -> ViewAssertion) {
for(index in indices) {
onView(this.atPosition(index)).let { viewMatcher ->
viewMatcher.check(assertionForIndex(index))
}
}
}
哪个应该起作用
R.id.multiselectview_recycler_view.matchAsRecyclerView().checkAtPositions(0, 1, 2, assertionForIndex = {
index -> RecyclerViewMatcher.isSelected(true)
})