Kotlin 和 Android Espresso 测试:添加带有接收器的扩展功能

Kotlin and Android Espresso tests: Adding extension function with receiver

我仍在努力提高我对接收器扩展功能的理解,需要各位专家的帮助来解决我的问题。

我有一个 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) 
})