3

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?

Nurseyit Tursunkulov
  • 8,012
  • 12
  • 44
  • 78
  • EspressoIdlingResource.increment() supposed to tell framework to wait until some background operation is done. But I use Flows and Espresso finishes it checks immediately without waiting – Nurseyit Tursunkulov Feb 15 '21 at 04:31

1 Answers1

6

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.

jeprubio
  • 17,312
  • 5
  • 45
  • 56