为什么 espressos 视图层次结构与 UI automators 视图层次结构不匹配

Why does espressos view hierarchy not match UI automators view hierarchy

这就是 espresso 转储视图层次结构的方式:

+------->AppBarLayout{id=-1, visibility=VISIBLE, width=1080, height=273, has-focus=false,...
|
+-------->Toolbar{id=2131296382, res-name=main_toolbar, visibility=VISIBLE, width=1080, height=147, ,...
|
+--------->AppCompatTextView{id=-1, visibility=VISIBLE, width=185, height=71, has-focus=false, ,...
|
+--------->AppCompatImageButton{id=-1, desc=Open navigation drawer, visibility=VISIBLE, width=147, height=147, ,...
|
+--------->ActionMenuView{id=-1, visibility=VISIBLE, width=359, height=147, has-focus=false, has-focusable=true, ,...
|
+---------->ActionMenuItemView{id=2131296286, res-name=action_toggle_location_service, desc=Toggle location service, ,...

层次结构查看器:

UI Automator 查看器:

令人困惑的是,从视觉上看,汉堡包菜单排在第一位,App-Title 排在第二位。

我遇到了以下测试:

    final ViewInteraction textView = onView(
            allOf(
                    withParent(withId(R.id.main_toolbar)),
                    withParentIndex(1)
            )
    );

    // Test fails!!! with withParentIndex(1)
    textView.check(matches(withText("MobiAd")));

以上示例适用于 withParentIndex(0)

有谁知道 UI-Automator 和浓缩咖啡之间的区别是错误还是有原因?

我做了一个小示例应用程序,我想我已经弄清楚发生了什么。 您正在测试的应用程序可能有一个由 setSupportActionBar().

设置的自定义工具栏

由于您的应用程序具有导航抽屉,汉堡包按钮将显示在您的自定义工具栏上,显然(如布局检查器所示)修改了其层次结构。

例如:

<android.support.v7.widget.Toolbar
    android:id="@+id/R.id.main_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#c13030">
    <!--This textview exists at index 0-->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MobiAd"/>
</android.support.v7.widget.Toolbar>

在您的 activity 中,您可能会发现这样的内容:

Toolbar toolbar = (Toolbar) findViewById(R.id.main_toolbar);

//here is the magic
setSupportActionBar(toolbar);

当导航抽屉按钮显示时,它作为它的一部分出现在工具栏上,但仍然,您的 textview 存在于索引 0,而不是 1。

如果您想查看真正的层次结构,只需查看工具栏中的内容(找到声明 R.id.main_toolbar 的布局文件)。

建议:为什么要通过查找索引来查找文本?如果它将被移动到另一个索引,您将不得不重构您的测试。 你可以使用它的字符串资源键(而不是写几行,你可以在一行代码中做一个简单的检查):onView(withText(R.string.toolbar_title)).check(matches(isDisplayed()));