java - 如何在 Espresso 中等待异步事件?

标签 java android android-espresso

我很困惑,Espresso 在处理失败时似乎有点不一致。

我想要实现的是重试检查要显示的某个字符串。单击按钮会启动异步操作,该操作应在某个时间范围内完成,并且我可以成功地在检查某些元素是否存在的周围放置一个 try catch block :

try {
    onView(withId(fieldIdToBeAvailable))
            .inRoot(isDialog())
            .check(matches(isDisplayed()));
}
catch (NoMatchingViewException nmve) {
    // ok, retry this or fail
    retry();
}

这会抛出 NoMatchingViewException 并使用某种循环重试此操作,但如果我尝试检查匹配的文本,例如 Espresso 不会抛出异常:

onView(withId(R.id.sync_status))
                .check(matches(withText("Logged in")));

唯一发生的事情是 android.support.test.espresso.base.DefaultFailureHandler$AssertionFailedWithCauseError:

有人会如何围绕这个编写重试概念?当我将 failureHandler 放置到位时,我无法抛出它(因此我会捕获异常而不是评估 AssertionFailed 错误),因为 handle 不允许抛出:

        onView(withId(R.id.sync_status)).withFailureHandler(new FailureHandler()
        {
            @Override
            public void handle(Throwable error, Matcher<View> viewMatcher)
            {
                // Compiler error: Unhandled exception
                throw new Exception("Failed, try again");
            }
        }).check(matches(withText("Logged in")));

最佳答案

我建议使用空闲资源来处理异步操作 https://developer.android.com/training/testing/espresso/idling-resource.html

无论如何,Exception 是一个已检查的异常,因此应该用 try-catch 包装它,或者方法应该使用 throws 关键字定义该异常。 要“修复”编译器错误,您可以使用 RuntimeExceptionError

关于java - 如何在 Espresso 中等待异步事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48753981/

相关文章:

java - 由于 RenderScript,Android 仪器测试失败

java - 将数据添加到 TreeView 列表

java - 为什么 Antlr 默认采用某些替代方案而不是其他方案?

Java Generics Hell - 传入这个但它想要类型 T

带有httpurlconnection的android api 23中的Java rest api

java - 由于 Android 消息 `Viewing full screen, To exit, swipe down from the top`,Espresso 测试失败

java - 每4个字符将char放入java字符串中

java - 仅当不为空时才将文件从 Assets 复制到害怕

android-manifest - 如何从 Java 向 Android 的主菜单网格动态添加新图标?

java - 在 Dalvik 运行时设备上运行 Espresso 仪器测试的问题