首页 > 解决方案 > Espresso 测试快速切换的 ProgressBar

问题描述

我有一个向服务器触发异步请求的活动。当它被触发时,我会显示一个进度条。当结果返回到活动时,我将进度条设置为 View.GONE。

我现在有两个测试。一种用于测试尝试使用错误凭据登录的方法,效果很好:

@Test
public void tryLogin__withWrongPassword() {
    onView(withId(R.id.loginEmail))
            .perform(typeText("em@ail.com"), closeSoftKeyboard());
    onView(withId(R.id.loginPassword))
            .perform(typeText("123456789"), closeSoftKeyboard());
    onView(withId(R.id.loginSubmit))
            .perform(click());
    onView(withId(R.id.loginProgressBar))
            .check(matches(isDisplayed()));

    onView(isRoot()).perform(waitFor(3000));

    onView(withId(R.id.loginProgressBar))
            .check(matches(not((isDisplayed()))));
    onView(withId(R.id.loginPassword))
            .check(matches(hasErrorText("Wrong password")));
}

我在没有互联网连接的情况下测试的一个不起作用:

@Test
public void tryLogin__withoutInternet() {
    onView(withId(R.id.loginEmail))
            .perform(typeText("em@ail.com"), closeSoftKeyboard());
    onView(withId(R.id.loginPassword))
            .perform(typeText("123456789"), closeSoftKeyboard());
    onView(withId(R.id.loginSubmit))
            .perform(click());
    onView(withId(R.id.loginProgressBar))
            .check(matches(isDisplayed()));

    onView(isRoot()).perform(waitFor(3000));

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

    onView(withText("Network error, try again later"))
            .inRoot(withDecorView(not(mActivityRule.getActivity().getWindow().getDecorView())))
            .check(matches(isDisplayed()));
}

测试失败,因为在这种情况下,进度条显示了几分之一秒(因为错误几乎立即从视图模型中分派)并且似乎 Espresso 在仍在加载时无法捕获它。

我的问题是如何在我的测试中解决这个问题?我在某处读到 Espresso 无法测试进度条,建议改用 UIAutomator,但是我刚开始使用 Instrumented 测试并选择了 Espresso,我很难找到适合这种情况的理想工具。此外,当进度条出现半秒多一点时,它似乎工作得很好(例如在我的第一个测试中)

PS waitFor(long millis) 方法是我制作的一种实用程序附加方法,用于强制 Espresso 在检查某些内容之前等待指定的时间(强制超时作为质量要求)

为澄清而编辑: 我的主要问题是,是否有人知道为什么当可见性处于活动状态的时间少于半秒而不是持续时间超过半秒时,即使检查是在之后立即完成的perform(click()) 调用。

标签: androidandroid-progressbarandroid-espressoui-testing

解决方案


推荐阅读