Kotlin和Android Espresso测试:使用接收器添加扩展功能



我仍在努力提高我对接收器的扩展功能的理解,并且需要对我有一个问题的专家提供一些帮助。

我有一个Android Espresso Testcase,我检查了我选择了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) 
})

相关内容