我仍在努力提高我对接收器扩展功能的理解,需要各位专家的帮助来解决我对此的疑问。
我有一个 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));
}
最佳答案
当然!
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)
})
关于android - Kotlin 和 Android Espresso 测试 : Adding extension function with receiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49511741/