如何使用R.ID访问父元素中的class名称元素



我正在编写一个自动测试,以登录到Android应用程序。我正在使用Record Espresso测试进行录制测试,然后编辑代码,因为它通常充满了错误。我正在使用浓缩咖啡 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,因此我想找到一种简单的方法来调用它们以进行测试。

在所有可能的组合中尝试了数十个不同的匹配器之后,我找到了问题的答案。到目前为止,它似乎是普遍的: onView(allOf(withClassName(containsString(EditText.class.getSimpleName())), isDescendantOfA(withId(R.id.til_name)))) .perform(replaceText("testespresso "), closeSoftKeyboard());

使用isDescendantOfA,我们不必担心我们正在寻找的元素具有带有R.id的父/祖父母,它只需要在层次结构中较低即可。

我认为您应该尝试此(在没有ID的情况下找到您的EDITTEXT,但具有独特的已知ID的父母(:

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

基于新信息的更新:与间接父级匹配(R.Id ....位于间接父母的ID(:

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

最新更新