Android Ui Testing: Why Livedata's Observers Are Not Being Called?
I have been trying, without success, to do some UI tests on Android. My app follows the MVVM architecture and uses Koin for DI. I followed this tutorial to properly set up a UI tes
Solution 1:
Finally found the problem and the solution with the debugger. Apparently, the @Before function call runs after the ViewModel is injected into the fragment, so even if the variables pointed to the same reference, mocked answer where executing only in the test context, not in the android context.
I changed the ViewModel initialization to the module scope like this:
@get:Ruleval fragmentRule = createRule(fragment, module {
single(override = true) {
makeMocks()
val twitchViewModel = mockViewModel()
twitchViewModel
}
})
privatefunmakeMocks() {
mockkStatic(Picasso::class)
}
privatefunmockViewModel(): TwitchViewModel {
val userData = MutableLiveData<UserDataResponse>()
val twitchViewModel = mockk<TwitchViewModel>(relaxed = true)
every { twitchViewModel.userData } returns userData
every { twitchViewModel.getUserByInput("Rubius") }.answers {
updateUserDataLiveData(userData)
}
return twitchViewModel
}
And the Observer inside the Fragment got called!
Maybe it's not related, but I could not rebuild the gradle project if I have mockk(v1.10.0) as a testImplementation and as a debugImplementation.
Post a Comment for "Android Ui Testing: Why Livedata's Observers Are Not Being Called?"