IdlingResource Espresso with RxJava

后端 未结 3 1304
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 09:21

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 r

3条回答
  •  旧巷少年郎
    2021-02-04 10:02

    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 callbacks;
    
    public IdlingApiServiceWrapper(MyRestService api) {
        this.api = api;
        this.callbacks = new ArrayList<>();
        this.counter = new AtomicInteger(0);
    }
    
    public Observable 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 {
    @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.

提交回复
热议问题