浓缩咖啡 - withEffectiveVisibility 与 isDisplayed

Espresso - withEffectiveVisibility vs isDisplayed

isDisplayedwithEffectiveVisibility 有什么区别?

onView(withText("Much Dagger")).check(matches(withEffectiveVisibility(ViewMatchers.Visibility.VISIBLE)));


onView(withText("Much Dagger")).check(matches(ViewMatchers.isDisplayed());

根据文档

Returns a matcher that matches {@link View}s that have "effective" visibility set to the given value. Effective visibility takes into account not only the view's visibility value, but also that of its ancestors. In case of View.VISIBLE, this means that the view and all of its ancestors have visibility=VISIBLE. In case of GONE and INVISIBLE, it's the opposite - any GONE or INVISIBLE parent will make all of its children have their effective visibility.

Note:

Contrary to what the name may imply, view visibility does not directly translate into whether the view is displayed on screen (use isDisplayed() for that). For example, the view and all of its ancestors can have visibility=VISIBLE, but the view may need to be scrolled to in order to be actually visible to the user. Unless you're specifically targeting the visibility value with your test, use isDisplayed.

因此,如果用于验证视图是否可见,请使用 isDisplayed() 但对于其他验证,如果不可见并消失,请使用 withEffectiveVisibilty()

正如前面的答案所暗示的那样,isDisplayed() 验证目标视图是否存在于屏幕的可见矩形中。但是,使用它有一个问题。根据官方文档,isDisplayed() -

select views that are partially displayed (eg: the full height/width of the view is greater than the height/width of the visible rectangle).

但实际上,这总是行不通的。如果目标视图在可见矩形中有超过 80% 可见,则只有 isDisplayed() 有效。但是如果您的视图的可见存在低于该阈值,那么您需要使用isDisplayingAtLeast()。此方法采用自定义百分比数量,您认为视图在可见矩形 中所占的比例。如果您的视图超出可见矩形(0% 可见)或在可见矩形中完全可见(100% 可见),这将不起作用。如果你想确保视图是否完全存在于可见的矩形中,那么你可以使用 isCompletelyDisplayed).

底线是,如果你想确保目标视图是否对用户可见(即作为用户,你可以在屏幕上看到它),然后选择 isDisplayed() 或它的其他变体。

现在进入 withEffectiveVisibility() 的目的。它基本上确保 Target 视图设置了所需的 Visibility 属性。它可以验证三个可见性状态 - VISIBLEINVISIBLEGONE。请记住,此验证不需要视图出现在可见矩形中。该视图只需要出现在视图层次结构中。当布局膨胀时,它会创建一个 ViewTree 并且您的视图可以位于该树中的任何位置(即在任何节点中)。他们在树中的可见性状态通过此方法验证。

所以最重要的是,当您想要验证当前位于可见矩形内部/外部的视图可见性状态时,您可以使用此方法。示例 - 如果您有一个可滚动布局,其中 CTA(即按钮)位于最底部并且与其交互会更改位于布局最顶部的视图的可见性状态,则无需滚动到布局顶部,您可以声明可见性状态更改。