Search code examples
android-espressoandroid-testingkotlin-flow

how to use Espresso with Kotlin Flow?


In my app I use Kotlin Flow. Before I used suspend function with EspressoIdlingResource.increment(), but it does not work with Kotlin Flow. How to solve this problem?


Solution

  • I've replicated your problem and then made it work.

    I needed to add in your gradle the espresso-idling-resource lib in implementation and androidTestImplementation:

    implementation 'androidx.test.espresso:espresso-idling-resource:3.3.0'
    androidTestImplementation 'androidx.test.espresso:espresso-idling-resource:3.3.0'
    

    This way I could create in my project the CountingIdlingResourceSingleton object:

    object CountingIdlingResourceSingleton {
    
        private const val RESOURCE = "GLOBAL"
    
        @JvmField val countingIdlingResource = CountingIdlingResource(RESOURCE)
    
        fun increment() {
            countingIdlingResource.increment()
        }
    
        fun decrement() {
            if (!countingIdlingResource.isIdleNow) {
                countingIdlingResource.decrement()
            }
        }
    }
    

    Then you should call this in your code when you want the test to wait, in my case it was in the onViewCreated() of the first fragment shown:

    CountingIdlingResourceSingleton.increment()
    

    And when the first flow element arrived I just called:

    CountingIdlingResourceSingleton.decrement()
    

    And finally add this in your test class to make it wait until the countingIdlingResource is decremented:

    init {
        IdlingRegistry.getInstance()
                .register(CountingIdlingResourceSingleton.countingIdlingResource)
    }
    
    @After
    fun unregisterIdlingResource() {
        IdlingRegistry.getInstance()
                .unregister(CountingIdlingResourceSingleton.countingIdlingResource)
    }
    

    With this the test that checked that the value matches the first value returned by flow (Jody) works.

    A working example can be find in github.com/jeprubio/waitflow where a flow element is emitted every 5 secs and the espresso test waits until the first element is emitted which is when the CountingIdlingResourceSingleton is decremented.