首页 > 解决方案 > simpli 从 esspresso android 中的自定义视图获取视图

问题描述

我在 android 中有一个具有这种布局的自定义组件。

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</androidx.constraintlayout.widget.ConstraintLayout>

在另一个布局中使用时,我通过此代码找到了 editText。(Espresso)

val editText = onView(
        allOf(withId(R.id.editText)
               , isDescendantOfA(withId(R.id.mainLayout))
               , isDescendantOfA(withId(R.id.mobileEdt))
        )
)

我在所有应用程序和许多布局中使用这个自定义组件。我可以在我的应用程序中缩小或转换为函数,因为不会一次又一次地写吗?

也许我改变了组件布局,所以我必须在所有测试中编辑所有 withId。

标签: androidtestingkotlinautomated-testsandroid-espresso

解决方案


您的组件可能有一个类名。比方说CustomEditText。在这种情况下,您可以实现一个BoundedMatcher基于自定义匹配器,以确保它只匹配您的CustomEditText.

简单的实现可能如下所示:

fun customEditWithId(idMatcher: Matcher<Int>): Matcher<View> {

    return object : BoundedMatcher<View, CustomEditText>(CustomEditText::class.java!!) {

        override fun describeTo(description: Description) {
            description.appendText("with id: ")
            idMatcher.describeTo(description)
        }

        override fun matchesSafely(textView: CustomEditText): Boolean {
            return idMatcher.matches(textView.id)
        }
    }
}

那么你的断言看起来像这样:

onView(customEditWithId(0)).perform(click());

推荐阅读