如何在Android或Android Espresso中获得视图层次结构

时间:2017-03-13 21:12:37

标签: android android-espresso android-testing

我正在使用Android Espresso,当找不到匹配项时,它会在打印视图层次结构时抛出异常。有没有办法在运行Android测试或Espresso

时动态获取此类视图层次结构
def insertEmployee(userOpt: Option[User], ...): Future[...] = {

  val userOptFut: Option[Future[User]] = userOpt.map { user => 
    userDao.insert(....) // returns a Future[User]
  }

  for {
    employee <- employeeDao.insert( Employee(..., ??, ......) )
  } yield ...

}

2 个答案:

答案 0 :(得分:3)

您可能会导致异常,然后将出现“视图层次结构”。例如,将其放入您的测试文件中:

onView(withText("XYZ")).perform(click())

并且由于文本XYZ不存在,结果将是:

...espresso.NoMatchingViewException: No views in hierarchy found matching: with text: is "XYZ"

View Hierarchy:
+>DecorView{id=-1, visibility=VISIBLE, width=1024, height=600, has-focus=true, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=1}
|
+->LinearLayout{id=-1, visibility=VISIBLE, width=1024, height=600, has-focus=true, has-focusable=true, has-window-focus=true, is-clickable=false, is-enabled=true, is-focused=false, is-focusable=false, is-layout-requested=false, is-selected=false, root-is-layout-requested=false, has-input-connection=false, x=0.0, y=0.0, child-count=2}
|
...

答案 1 :(得分:1)

鉴于Android View hierarchy是树结构,使用某种算法迭代每个树节点更容易,您可以在https://developer.android.com/reference/android/support/test/espresso/util/TreeIterables.html

查看这些方法

打印出Exception跟踪的方式使用名为breadthFirstViewTraversal的方法并在类ViewFinderImpl中打印出视图树 https://developer.android.com/reference/android/support/test/espresso/base/ViewFinderImpl.html