Android Espresso - wait for asynchronous load

烂漫一生 提交于 2019-12-12 01:19:59

问题


I have a RecyclerView into which data is loaded asynchronously.

The underlying engine does not use AsyncTasks, but java Executor.

How do I make Espresso to wait (or check periodically), with a timeout, until a given condition is met?

I've read about IdlingResource, but it seems to me like digging too deep, on a case-by-case basis, where there could exist something general-purpose, that could periodically check for a condition, until it is fulfilled or timeout happens.

Couldn't it just check, every few-hundred milliseconds, if the condition is met? Without the need to delve into the inner workings... Would that be a performance problem?


回答1:


You can use something like a waitFor method.

public class WaitAction implements ViewAction {

  /** The amount of time to allow the main thread to loop between checks. */

  private final Matcher<View> condition;
  private final long timeoutMs;

  public WaitAction(Matcher<View> condition, long timeout) {
    this.condition = condition;
    this.timeoutMs = timeout
  }

  @Override
  public Matcher<View> getConstraints() {
    return (Matcher) anything();
  }

  @Override
  public String getDescription() {
    return "wait";
  }

  @Override
  public void perform(UiController controller, View view) {
    controller.loopMainThreadUntilIdle();
    final long startTime = System.currentTimeMillis();
    final long endTime = startTime + timeoutMs;

    while (System.currentTimeMillis() < endTime) {
      if (condition.matches(view)) {
        return;
      }

      controller.loopMainThreadForAtLeast(100);
    }

    // Timeout.
    throw new PerformException();
  }

  public static ViewAction waitFor(Matcher<View> condition, long timeout) {
    return new WaitAction(condition, timeout);
  }
}

You can use this as following

onView(<some view matcher>).perform(WaitAction.waitFor(<Some condition>));


来源:https://stackoverflow.com/questions/41640888/android-espresso-wait-for-asynchronous-load

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!