Search code examples
androidandroidxandroid-livedataandroid-architecture-componentsandroid-jetpack

How to switch out AndroidX Architecture Component task executor for Espresso tests


We've run into problems with a flakey Espresso tests and are pretty certain the cause is a LiveData#postValue call. It seems Espresso will sometimes make assertions before all tasks have been executed on the ArchTaskExecutor instance.

It seemed to me that this problem should be solveable with use of IdlingResource: we could swap out the ArchTaskExecutor for one we integrate with CountingIdlingResource to make sure Espresso is aware of tasks being executed. It seems however that it isn't possible to set the executor being used as ArchTaskExecutor#setDelegate is only available within the arch library itself. We could of course stop using postValue and use a Handler (with the main looper) integrated with CountingIdlingResource. So we don't have to do that is there any other way of switching out or integrating with the ArchTaskExecutor to have Espresso be aware of when and when not it's idle?


Solution

  • After doing some digging I found that CountingTaskExecutorRule is available in the AndroidX Arch package. This can be used to build out an idling resource like so:

    public class CountingTaskExecutorIdlingResource extends CountingTaskExecutorRule implements IdlingResource {
    
        private IdlingResource.ResourceCallback resourceCallback;
    
        @Override
        public String getName() {
            return CountingTaskExecutorIdlingResource.class.getName();
        }
    
        @Override
        public boolean isIdleNow() {
            return isIdle();
        }
    
        @Override
        public void registerIdleTransitionCallback(IdlingResource.ResourceCallback resourceCallback) {
            this.resourceCallback = resourceCallback;
        }
    
        @Override
        protected void onIdle() {
            resourceCallback.onTransitionToIdle();
        }
    }