Archie
05/24/2020, 3:35 PMclass 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:
...
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.fatih
05/24/2020, 7:09 PMAsyncTask.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
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/testsfatih
05/24/2020, 7:19 PMkaptAndroidTest "com.google.dagger:dagger-compiler:$rootProject.dagger"
kaptAndroidTest "com.google.dagger:dagger-android-processor:$rootProject.dagger"
Archie
05/26/2020, 6:24 AMAsyncTask.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.fatih
05/26/2020, 10:23 AMfatih
05/26/2020, 10:24 AMArchie
05/26/2020, 2:57 PMfatih
05/26/2020, 2:57 PM