Issue
I am using espresso for testing and I am getting an error while executing below method.
viewModel.getData().observe(viewLifecycleOwner, Observer { options ->
Log.d(TAG, "onViewCreated: $options")
val data = options.filter { option -> option.type!! == OptionType.DATA}
updateData.updateUIComponent(data)
})
get data method return a LiveData object. and this is working fine in the Fragments but not workng in the espresso test class
Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
This is my test class
@LargeTest
@RunWith(AndroidJUnit4::class)
open class BaseIntegrationTest {
@get:Rule
val instantTestExecutorRule = InstantTaskExecutorRule()
lateinit var navController: TestNavHostController
lateinit var fragmentScenario: FragmentScenario<DetailsFragment>
@Before
fun initTest() {
navController = TestNavHostController(
ApplicationProvider.getApplicationContext()
)
}
@Test
fun launchFragment() {
val bundle = Bundle()
fragmentScenario =
launchFragmentInContainer(bundle, themeResId = R.style.Theme_mainTheme)
fragmentScenario.moveToState(Lifecycle.State.STARTED)
UiThreadStatement.runOnUiThread {
navController.setGraph(R.navigation.app_navigation_graph)
}
fragmentScenario.onFragment { fragment ->
//CollectFeedbackFragment()
Navigation.setViewNavController(fragment.requireView(), navController)
}
onView(withId(R.id.progressBar)).isVisible()
}
}
Solution
I managed to fix this issue By using Dispatchers.IO and Dispatchers.Main
class SampleViewModel : ViewModel() {
fun getData():DataLiveData {
viewModelScope.launch {
withContext(Dispatchers.IO) {
// here I am seding the Room db call
withContext(Dispatchers.Main) {
// I am updating the MutableLiveData object here
}
}
}
return mutableLiveData
}
}
And don't forget to inject dispatchers instead of hardcoding. Click here!
Answered By - Prasa Dev
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.