MatchingViewException 匹配(not (isDisplay()))失败

我试图测试 UI 视图的缺失。视图选择器如下:

public static ViewInteraction onMyTestUi() {
return onView(withId(R.id.myTestId));
}

选择器可以很好地检查视图是否显示,但如果检查视图未显示,则会出错。我使用的方法如下:

 onMyTestUi().check(matches(not(isDisplayed())));

但我得到了以下错误:

Com.google.android.apps.common.testing.ui.espresso.NoMatchingViewException: 在层次结构中找不到匹配的视图: 目标视图不是视图层次结构的一部分,您可能需要使用 OnData 从下列操作之一加载它 AdapterViews: android.widget. ListView { ... }

真奇怪。我正在检查是否缺少 UI,并且预计不会找到这个视图。那为什么浓缩咖啡会出错呢? 请告诉我这里可能出了什么问题。

谢谢, 太神奇了!

53137 次浏览

Need to use doesNotExist() instead. Found here.

If the view is there in the view hierarchy but in an invisible state (visibility is set to 'INVISIBLE'), use not(isDisplayed). However, if the view is not there at all in the view hierarchy (e.g. visibility set to 'GONE'), doesNotExist() is used.

onView(withText("")).check(doesNotExist());

Also work with yours method, but something like this:

onView(withId(R.id.next)).check(matches(not(isDisplayed())));

If you want to check if View is either not visible or does not exist.

public static ViewAssertion isNotDisplayed() {
return new ViewAssertion() {
@Override
public void check(View view, NoMatchingViewException noView) {
if (view != null && isDisplayed().matches(view)) {
throw new AssertionError("View is present in the hierarchy and Displayed: "
+ HumanReadables.describe(view));
}
}
};
}

Usage:

onView(withId(R.id.someView)).check(isNotDisplayed());

You can try this option if you check the view visibility "withEffectiveVisibility"

    onView(withId(R.id.YOURVIEW)).check(matches(ViewMatchers.withEffectiveVisibility(ViewMatchers.Visibility.GONE)))