android - Kotlin 和 Android Espresso 测试 : Adding extension function with receiver

标签 android kotlin android-espresso kotlin-extension

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

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

相关文章:

android - 错误 :(50, 28) 找不到与给定名称匹配的资源(在 'value' 处,值为 '@string/google_maps_key')

android - 调用 getGraph() 之前必须先调用 setGraph()

android - Android中带有标题的边框

android - 协程限制?

android - Kotlin 在后台线程上运行阻塞

android - 如何使用 espresso 按下 AlertDialog 按钮

android - "Attempt to read from field ' int android.content.pm.ApplicationInfo.targetSdkVersion ' on a null object reference"异常

java - 如何使用 "LIKE"和 "%"检查 android 中变量的相似性(Java 代码)

android - 如何在 Android 中创建自定义控件?

java - 安卓工作室 : Espresso dependencies in gradle