Hi Guys, I was wondering whether anyone has been t...
# android
a
Hi Guys, I was wondering whether anyone has been testing coroutine with Espresso? it is a common pattern with MVVM to do something like:
Copy code
class AViewModel() : ViewModel() {
    val liveData = MutableLiveData<SomeData>()
    ...
    fun doSomething() {
        viewModelScope.launch {
            //... do some long operation ....
            liveData.value = resultOfLongOperation
        }
    }
}
and observe the live data in Fragment or Activity like:
Copy code
...
    val viewModel by viewModels<AViewModel> { ... }
    ...
    fun onViewCreate(...) {
        button.setOnclickListener {
            viewModel.doSomething()
        }
        
        viewModel.liveData.observe(viewLifecycle, Observer { result ->
        textView.text = result
    })
    }
...
I was wondering how to do UI test for the Code above. Since the
doSomething()
takes a while to complete, my
Espresso
test is failing. Can anyone share how they do their test? Thank you very much.
f
You have to inject the dispatcher and use
AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher()
in UI tests since espresso knows there is a background task and waits for that task to be finished with this dispatcher. If you are using dagger 1- Create a
TestAppComponent
and override Coroutine dispatchers with a module and use
AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher() for <http://Dispatcers.IO|Dispatcers.IO> and Dispatchers.Default
2- Create a
TestApplication
which overrides your custom
Application
class and inject
DaggerTestAppComponent
like
Copy code
override fun applicationInjector(): AndroidInjector<out DaggerApplication> {
        return DaggerTestAppComponent.builder().create(this)
    }
3- Create a
CustomTestRunner
and override
newApplication
to be able to use
TestApplication
4- Give this
CustomTestRunner
in your gradle file as a test runner You can check it out from Android Developer Summit app 👉🏼 https://github.com/google/iosched/tree/adssched/mobile/src/androidTest/java/com/google/samples/apps/iosched/tests
And don't forget to add dagger for instrumentation tests too
Copy code
kaptAndroidTest "com.google.dagger:dagger-compiler:$rootProject.dagger"
    kaptAndroidTest "com.google.dagger:dagger-android-processor:$rootProject.dagger"
a
This is the interesting bit
AsyncTask.THREAD_POOL_EXECUTOR.asCoroutineDispatcher()
I never knew you could do that.. hmmm... I will do try that. I also came across this github thread here: https://github.com/Kotlin/kotlinx.coroutines/issues/242 I'm kinda curious whatcha think about it.
f
Idling resource needs refactoring the production code which I dont prefer. Think it like you have a piece of code which does nothing in production
I also double checked with @Manuel Vivo and he also suggested as I mentioned
a
Very informative thank you very much ❤️
f
Np 😄 happy to help