PistolPete
PistolPete

Reputation: 784

Wait for button dependent on network call in Espresso tests

I want to verify the existence of a button drawn in a fragment. The visibility and existence of the button is dependent upon a network call/response done with Retrofit.

Due to the asynchronous nature I thought I should go with IdlingResource. My problem is that I really don't know what a good approach would be for a true response in isIdleNow(). Should I try to get a hold hold of the element with findElementById(R..) or is there some other typical "Espresso way" of doing these wait assertions?

Edit:

Current solution is simply without IdlingResource:

while (timeout-- > 0) {
    try {
        onView(withId(element)).check(matches(isDisplayed()));
    } catch (AssertionError ae) {
        MiscUtil.sleep(1000);
        continue;
    }
    return true;
}

But I guess this is not according to Espresso fundamentals. Doing the check-matches call from an IdlingResource implementation suspended all threads for some reason.

Upvotes: 1

Views: 2625

Answers (1)

originx
originx

Reputation: 496

If you are using Retrofit I will presume you are using OKHttp if not then answer will be similar

(you just need to write an Idling Resource for your network operations.)

If you use OKHttp there is a nice out of the box idling resource here: https://github.com/JakeWharton/okhttp-idling-resource

In the setup of your test just inject your okhttp client (if you are using dagger), register the resource (DONT forget to unregister in tear down).

And your button visibility and showing will be auto magically waited upon.

Side note: be careful when it comes to animating your views they are your biggest enemy in instrumentation tests, make sure to disable animations (especially if you done them in a custom way you need to find a way to disable them during test runs).

Upvotes: 4

Related Questions