Snackbar 和 Espresso 有时会失败

Snackbar and Espresso failing sometimes

正如标题所说,有时失败,有时成功。

android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError: 'is displayed on the screen to the user' doesn't match the selected view.

Expected: is displayed on the screen to the user
Got: "AppCompatTextView{id=2131492981, res-name=snackbar_text, visibility=VISIBLE, width=444, height=71, has-focus=false, has-focusable=false, 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=18.0, y=0.0, text=Network Error, input-type=0, ime-target=false, has-links=false}"

堆栈跟踪的第一行表明 espresso 无法在屏幕上看到 Snackbar。但是第二行说明它实际上看到了带有 visibility=VISIBLEtext=Network Error 的 Snackbar,这是正确的。

我很困惑,这是怎么回事?

这是我的测试代码:

activityRule.launchActivity(new Intent());
onView(withText("Network Error")).check(matches(isDisplayed()));

PS:当我运行整个测试服时,它主要失败;但有时当我单独 运行 这个测试时它也会失败。有时它通过绿色,但没有任何图案,似乎是随机的。

晚了!但我希望它对其他人有帮助:

private void checkSnackBarDisplayedByMessage(@StringRes int message) {
    onView(withText(message))
        .check(matches(withEffectiveVisibility(
            ViewMatchers.Visibility.VISIBLE
    )));
}

我遇到了类似的问题。我能够通过以下方式解决它:

  1. 按照描述禁用动画 here

  2. 我在从服务器获取数据后显示 SnackBar,所以我还必须等到数据被获取。我设法用 IdlingResource as described in anwser.

  3. 解决了它

然后我可以成功检查SnackBar。

希望我的观点对您有所帮助。