【问题标题】:Testing Snackbar show with Espresso用 Espresso 测试 Snackbar 节目
【发布时间】:2015-10-13 20:19:25
【问题描述】:

有没有办法使用 Espresso 测试小吃栏是否显示正确的文本?

我有一个简单的调用来创建一个小吃店

Snackbar.make(mView, "My text", Snackbar.LENGTH_LONG).show();

我试过这个没有运气

onView(withText("My text")).inRoot(withDecorView(not(is(mActivityRule.getActivity().getWindow().getDecorView())))).check(matches(isDisplayed()));

【问题讨论】:

    标签: android integration-testing android-testing android-espresso android-snackbar


    【解决方案1】:

    这对我有用,请尝试。

    onView(allOf(withId(android.support.design.R.id.snackbar_text), withText("My text")))
                .check(matches(isDisplayed()));
    

    如果您使用AndroidX,请使用以下:

    onView(withId(com.google.android.material.R.id.snackbar_text))
            .check(matches(withText(R.string.whatever_is_your_text)))
    

    【讨论】:

    • 当 espresso 在snackbar 的Y 位置是0.0 时进行检查,你会怎么做? isDisplayed 抛出异常。
    • 确保在 y 位置为 0.0 时不添加此断言,这意味着您的小吃店已完成显示或尚未显示。您可能需要调整测试以确保您要么等到它显示出来,要么提前检查一下,这取决于您的场景
    • @ksarmalkar 那么我们应该如何等待呢?
    • 一种方法是添加您自己的匹配器,该匹配器每隔几毫秒轮询一次,并设置一个最大超时时间,这样它就不会无限期地运行。很确定可能有很多其他方法可以处理这个问题。很少有人想到,添加一个监听器来关闭快餐栏并失败,以防永远不会调用关闭,表明从未显示过小吃吧。
    • 我收到了NoMatchingViewException: No views in hierarchy found matching: with id: com.my.package.debug:id/snackbar_text。有什么想法吗?
    【解决方案2】:

    另一种选择

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

    【讨论】:

    • 完美,我认为可以用于所有通用文本
    • 使用 withEffectiveVisibility 而不是 isDisplayed 所以不管它是否实际显示在当前屏幕上。
    【解决方案3】:

    我看到了以前的答案,但我认为这会更好。

    @Test
    public void onFabClick_shouldDisplaySnackbar() throws Exception {
      onView(withId(R.id.fab)).perform(click());
    
      // Compare with the text message of snackbar
      onView(withText(R.string.snackbar_message))
          .check(matches(isDisplayed()));
    }
    

    【讨论】:

    • 我们从哪里导入“withText”?
    • @Phlip 像这样导入:import android.support.test.espresso.matcher.ViewMatchers.withText
    猜你喜欢
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多