问题
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