Espresso how to wait for some time(1 hour)?
You need an IdlingResource
with an isIdleNow()
that returns true
only if the specific amount of time has passed. To achieve that, save the start time and compare it with current time:
public class ElapsedTimeIdlingResource implements IdlingResource { private final long startTime; private final long waitingTime; private ResourceCallback resourceCallback; public ElapsedTimeIdlingResource(long waitingTime) { this.startTime = System.currentTimeMillis(); this.waitingTime = waitingTime; } @Override public String getName() { return ElapsedTimeIdlingResource.class.getName() + ":" + waitingTime; } @Override public boolean isIdleNow() { long elapsed = System.currentTimeMillis() - startTime; boolean idle = (elapsed >= waitingTime); if (idle) { resourceCallback.onTransitionToIdle(); } return idle; } @Override public void registerIdleTransitionCallback( ResourceCallback resourceCallback) { this.resourceCallback = resourceCallback; }}
Create and register this idling resource in your test:
@Testpublic static void waitForOneHour() { long waitingTime = DateUtils.HOUR_IN_MILLIS; // Start onView(withId(AaEspressoTest.getId("recorderpage_record"))) .perform(click()); // Make sure Espresso does not time out IdlingPolicies.setMasterPolicyTimeout( waitingTime * 2, TimeUnit.MILLISECONDS); IdlingPolicies.setIdlingResourceTimeout( waitingTime * 2, TimeUnit.MILLISECONDS); // Now we wait IdlingResource idlingResource = new ElapsedTimeIdlingResource(waitingTime); Espresso.registerIdlingResources(idlingResource); // Stop onView(withId(AaEspressoTest.getId("recorderpage_stop"))) .perform(click()); // Clean up Espresso.unregisterIdlingResources(idlingResource);}
You need the setMasterPolicyTimeout
and setIdlingResourceTimeout
calls to make sure Espresso does not terminate the test due to time out.
Full example: https://github.com/chiuki/espresso-samples/tree/master/idling-resource-elapsed-time
The default timeout that Espresso will wait for all registered resources to become idle is one minute.
You can change this using the IdlingPolicies
class to set an explicit timeout:
IdlingPolicies.setIdlingResourceTimeout(1, TimeUnit.HOURS);
@Beforepublic void registerIdlingResource() { IdlingPolicies.setMasterPolicyTimeout(60 * 1000 * 3, TimeUnit.MILLISECONDS); IdlingPolicies.setIdlingResourceTimeout(60 * 1000 * 3, TimeUnit.MILLISECONDS); mIdlingResource = BooleanIdlingResource.getIdlingResource(); // To prove that the test fails, omit this call: IdlingRegistry.getInstance().register(mIdlingResource);}
I test on my project, It works.Just setup before register idling resources.please check:
https://github.com/googlesamples/android-testing/tree/master/ui/espresso/IdlingResourceSampleand
https://developer.android.com/reference/android/support/test/espresso/IdlingPolicies