Skip to content

Instantly share code, notes, and snippets.

@Maragues
Last active August 10, 2016 09:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Maragues/0c0db81a137c8d067396 to your computer and use it in GitHub Desktop.
Save Maragues/0c0db81a137c8d067396 to your computer and use it in GitHub Desktop.
Implementation and usage of an IdlingResource that waits for Picasso actions to finish.

Note that the file lives in the package as Picasso. Otherwise we don't have access to targetToAction

package com.squareup.picasso;

public class PicassoIdlingResource implements IdlingResource, ActivityLifecycleCallback {
  protected ResourceCallback callback;

  WeakReference<Picasso> picassoWeakReference;

  @Override
  public String getName() {
    return "PicassoIdlingResource";
  }

  @Override
  public boolean isIdleNow() {
    if (isIdle()) {
      notifyDone();
      return true;
    } else {
      return false;
    }
  }

  public boolean isIdle() {
    return picassoWeakReference == null
            || picassoWeakReference.get() == null
            || picassoWeakReference.get().targetToAction.isEmpty();
  }

  @Override
  public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
    this.callback = resourceCallback;
  }

  void notifyDone() {
    if (callback != null) {
      callback.onTransitionToIdle();
    }
  }

  @Override
  public void onActivityLifecycleChanged(Activity activity, Stage stage) {
    switch (stage) {
      case CREATED:
        picassoWeakReference = new WeakReference<>(Picasso.with(activity));
        break;
      case STOPPED:
        // Clean up reference
        picassoWeakReference = null;
        break;
      default: // NOP
    }
  }
}

USAGE

  @Before
  protected void setUp() throws Exception {
    super.setUp();
    
    Espresso.registerIdlingResources(mPicassoIdlingResource);

    ActivityLifecycleMonitorRegistry
            .getInstance()
            .addLifecycleCallback(mPicassoIdlingResource);
  }
  
  @After
  protected void tearDown() throws Exception {
    super.tearDown();
    
    Espresso.unregisterIdlingResources(mPicassoIdlingResource);
  }
@Maragues
Copy link
Author

There's at least one flaw that I know of. If your code passes null as the path to load, this idlingresource does not wait for the placeholder drawable to be used in the ImageView.

I'm sure there are more errors and better ways to implement this, but it's working for my tests.

@sebaslogen
Copy link

Hi, I forked this gist and updated it with a couple of improvements to handle multiple Activities and execute tests faster:
https://gist.github.com/sebaslogen/0b2fdea3f322c730e04b0af7285fcd28

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment