首页 > 解决方案 > 如何通过类名访问具有 R.id 的父元素中的元素

问题描述

我正在编写一个用于登录 Android 应用程序的自动化测试。我正在使用 Record Espresso Test 记录测试,然后编辑代码,因为它通常充满错误。我正在使用浓缩咖啡 androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2',uiAutomatorViewer仔细检查R.id's~class名称。

我在尝试编辑元素中没有R.id但使用类名的文本时遇到了问题android.widget.EditText

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: (with id: com.mydosesmart:id/til_name and an instance of android.widget.FrameLayout and an instance of android.widget.EditText)

问题是具有类名的元素android.widget.EditText 没有R.id.. 这个类名对于这个视图不是唯一的,这个具有类名android.widget.EditText的元素有一个具有唯一性的父元素R.id.

在应用程序的登录视图中,两个元素具有类名,android.widget.EditText因此我不能仅通过类名来调用此元素。我想这样称呼它:在元素中R.id.til_name找到具有类名的元素android.widget.EditText。下面是我现在使用的代码,但它失败了。

ViewInteraction textInputEditText2 = onView(
                allOf(withId(R.id.til_name), instanceOf(Class.forName("android.widget.FrameLayout")), instanceOf(Class.forName("android.widget.EditText"))));
        textInputEditText2.perform(replaceText("testespresso"), closeSoftKeyboard());

这也失败了:

ViewInteraction textInputEditText2 = onView(
                allOf(withId(R.id.til_name), instanceOf(Class.forName("android.widget.EditText"))));
        textInputEditText2.perform(replaceText("testespresso"), closeSoftKeyboard());

由于我正在测试的应用程序中的许多元素没有指定的 R.id,我想找到一种简单的方法来调用它们以进行测试。

标签: androidandroid-espressomatcherandroid-espresso-recorder

解决方案


我认为你应该试试这个(找到你的 EditText 没有 ID 但有唯一已知 id 的父级):

allOf(withParent(withId(R.id...)), withClassName(containsString(EditText.class.getName())))

根据新信息更新:与间接父级匹配(R.id.... 是放置间接父级 ID 的位置):

allOf(isDescendantOfA(withId(R.id...)), withClassName(containsString(EditText.class.getName())))

推荐阅读