Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IdlingResource Espresso with RxJava

I recently converted my application from using async tasks to rxjava. Now, my espresso tests no longer wait for my data calls to complete due to espresso not having an idling resources for rxjava. I noticed that you can make custom idling resources but I can't figure out how to make it work with rxJava Schedulers, Scheduler.io specifically. Any help/best practice would be greatly appreciated.

like image 962
FriendlyMikhail Avatar asked Nov 25 '14 22:11

FriendlyMikhail


1 Answers

Here is how I solved the problem:

IdlingResource implementation:

public class IdlingApiServiceWrapper implements MyRestService, IdlingResource {

private final MyRestService           api;
private final AtomicInteger counter;
private final List<ResourceCallback> callbacks;

public IdlingApiServiceWrapper(MyRestService api) {
    this.api = api;
    this.callbacks = new ArrayList<>();
    this.counter = new AtomicInteger(0);
}

public Observable<MyData> loadData(){
    counter.incrementAndGet();
    return api.loadData().finallyDo(new Action0() {
        @Override
        public void call() {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    counter.decrementAndGet();
                    notifyIdle();
                }
            });
        }
    });
}

@Override public String getName() {
    return this.getClass().getName();
}

@Override public boolean isIdleNow() {
    return counter.get() == 0;
}

@Override public void registerIdleTransitionCallback(ResourceCallback resourceCallback) {
    callbacks.add(resourceCallback);
}

private void notifyIdle() {
    if (counter.get() == 0) {
        for (ResourceCallback cb : callbacks) {
            cb.onTransitionToIdle();
        }
    }
   }
   }

and here is my test:

public class MyActivityTest extends ActivityInstrumentationTestCase2<MyActivity> {
@Inject
IdlingApiServiceWrapper idlingApiWrapper;

@Override
public void setUp() throws Exception {
    //object graph creation

    super.setUp();
    getActivity();
    Espresso.registerIdlingResources(idlingApiWrapper);
}

public void testClickOpenFirstSavedOffer() throws Exception {
    onData(is(instanceOf(DataItem.class)))
            .atPosition(0)
            .perform(click());
   }
  }

I used Dagger for dependency injection.

like image 188
Hua H. Avatar answered Oct 21 '22 22:10

Hua H.