Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 212
Nurseyit Tursunkulov Avatar asked Oct 14 '25 08:10

Nurseyit Tursunkulov


1 Answers

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.

like image 106
jeprubio Avatar answered Oct 17 '25 19:10

jeprubio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!