【问题标题】:Wait For Matcher in Espresso Java/Android在 Espresso Java/Android 中等待 Matcher
【发布时间】:2017-03-17 18:53:50
【问题描述】:

我从 here 中发现了一段非常酷的代码,它有助于执行等待功能,直到出现资源 withId(int) - 当我实际上有一个资源 ID 可以使用时,它似乎工作正常。

但是,我正在使用的应用程序通常没有简单的资源 ID,而我必须使用 Matchers。

一个例子:

Matcher secondBanner = allOf(childAtPosition(allOf(withId(R.id.story_details_body),
                childAtPosition(IsInstanceOf.<View>instanceOf(
                android.widget.LinearLayout.class),2)),0)))

有没有办法在 Matcher 上执行类似的等待,就像有资源 id 一样?

我在上一个链接中指的代码是-

/** Perform action of waiting for a specific view id. */
public static ViewAction waitId(final int viewId, final long millis) {
  return new ViewAction() {
    @Override
    public Matcher<View> getConstraints() {
        return isRoot();
    }

    @Override
    public String getDescription() {
        return "wait for a specific view with id <" + viewId + "> during " + millis + " millis.";
    }

    @Override
    public void perform(final UiController uiController, final View view) {
        uiController.loopMainThreadUntilIdle();
        final long startTime = System.currentTimeMillis();
        final long endTime = startTime + millis;
        final Matcher<View> viewMatcher = withId(viewId);

        do {
            for (View child : TreeIterables.breadthFirstViewTraversal(view)) {
                // found view with required ID
                if (viewMatcher.matches(child)) {
                    return;
                }
            }

            uiController.loopMainThreadForAtLeast(50);
        }
        while (System.currentTimeMillis() < endTime);

        // timeout happens
        throw new PerformException.Builder()
                .withActionDescription(this.getDescription())
                .withViewDescription(HumanReadables.describe(view))
                .withCause(new TimeoutException())
                .build();
    }
};
}

我试图简单地将所有内容从 withId(int) 更改为 Matcher 无济于事。

那么有没有可能把这段代码变成可以执行等待/超时的东西?

感谢您的任何帮助。

【问题讨论】:

    标签: java android unit-testing junit android-espresso


    【解决方案1】:

    您可以简单地使用Thread.sleep(timeInMilisec)。它会按原样等待一段时间。

    或

    Idling Resources 没关系,但是你需要添加一些额外的代码,不仅在测试中,而且在你的项目中。您可以在代码中指定测试应该等待的时间以及应该再次进行的时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-11
      相关资源
      最近更新 更多