Espresso wait for view to appear

15 July 2019 Stephan Petzl Leave a comment Tech-Help

Let’s say you want to press a button in your test automation, but the button is only shown after a server response arrived. How to we make Espresso wait for the view to appear? One way achieve this is to implement an idling resource which tells the test runner to wait till it is indicating that the button is shown. We already wrote a post about the basics of idling resources and why we need them earlier. We also introduced an alternative to idling resources here.

Just a couple of notes before we show the implementation:

  1. Remember that you don’t want to unregister all IdlingResources when you unregister your AmountViewIdlingResource, keep a reference to it and only unregister that reference, don’t unregister all IdlingResources.
  2. To create an instance for your view you will need a reference to that view first. Use findViewById or a similar method for that.

 

public class ButtonVisibilityIdlingResource implements IdlingResource {

    private final View mButton;
    private final int mExpectedVisibility;

    private boolean mIdle;

    public ViewVisibilityIdlingResource(final View button, final int expectedVisibility) {
        this.mIdle = false;
        this.mButton = button;
        this.mExpectedVisibility = expectedVisibility;
    }

    @Override
    public final String getName() {
        return ButtonVisibilityIdlingResource.class.getSimpleName();
    }

    @Override
    public final boolean isIdleNow() {
        mIdle = mIdle || mButton.getVisibility() == mExpectedVisibility;
        return mIdle;
    }
}

Like this article? there’s more where that came from.

Leave a Reply