Last active
July 9, 2019 06:47
-
-
Save lukasdylan/91a6591c903d3d69245904f66b54241b to your computer and use it in GitHub Desktop.
Espresso Idling Resource with Coroutines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.lukasdylan.dicoding.made.utils | |
import androidx.annotation.VisibleForTesting | |
import kotlinx.coroutines.CoroutineDispatcher | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.ExperimentalCoroutinesApi | |
interface DispatcherProvider { | |
val main: CoroutineDispatcher | |
val background: CoroutineDispatcher | |
val commonPool: CoroutineDispatcher | |
} | |
class DispatcherProviderImpl : DispatcherProvider { | |
override val main: CoroutineDispatcher | |
get() = Dispatchers.Main | |
override val background: CoroutineDispatcher | |
get() = Dispatchers.IO | |
override val commonPool: CoroutineDispatcher | |
get() = Dispatchers.Default | |
} | |
@ExperimentalCoroutinesApi | |
@VisibleForTesting | |
class TestDispatcherProvider : DispatcherProvider { | |
override val main: CoroutineDispatcher | |
get() = Dispatchers.Unconfined | |
override val background: CoroutineDispatcher | |
get() = Dispatchers.Unconfined | |
override val commonPool: CoroutineDispatcher | |
get() = Dispatchers.Unconfined | |
} | |
fun DispatcherProvider.espressoIdlingResource(increment: Boolean) { | |
/** | |
* When we initialize [androidx.test.espresso.idling.CountingIdlingResource] on [EspressoIdlingResource] object, | |
* they need to check a string whether is empty or not using TextUtils.isEmpty(), thus this method cannot be mocked | |
* on Unit Test. So we need to check the [kotlinx.coroutines.CoroutineDispatcher] if it used [Dispatchers.Main] | |
* instead of [Dispatchers.Unconfined] on Unit Test | |
*/ | |
if (this.main == Dispatchers.Main) { | |
if (increment) { | |
EspressoIdlingResource.increment() | |
} else { | |
EspressoIdlingResource.decrement() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment