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

时间:2018-02-12 19:22:08

标签: java android android-espresso

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

我尝试实现的是重新检查要显示的某个字符串。单击按钮将启动应在一段时间内完成的异步操作,并且我可以成功地在检查是否存在某个元素时设置try catch块:

    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")));

1 个答案:

答案 0 :(得分:1)

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

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

相关问题