So, i want to test my livedata of paging on viewmodel that changing based on token mutablestateflow. Here is my viewModel
class MainViewModel(private val repository: UserRepository) : ViewModel() {
private val token = MutableLiveData<String>()
val data: LiveData<PagingData<RemoteItems>> = token.switchMap {
repository.getItems(it)
}
val refresh = repository.refresh
fun getSession() = viewModelScope.launch {
repository.getSession().collectLatest {
token.value = it.token
}
}
fun logout() {
viewModelScope.launch {
repository.logout()
}
}
fun refreshed() {
repository.refreshed()
}
}
So, i make a test with robolectric and junit for this viewModel. Here is my test:
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(RobolectricTestRunner::class)
class MainViewModelTest {
@get:Rule
val executorRule: InstantTaskExecutorRule = InstantTaskExecutorRule()
@get:Rule
val coroutineRule: MainDispatcherRule = MainDispatcherRule()
private lateinit var viewModel: MainViewModel
private lateinit var repository: UserRepository
private val context = RuntimeEnvironment.getApplication().applicationContext
@Before
fun setup() {
repository = UserRepository.getInstance(
UserPreference.getInstance(context.dataStore),
UnconfinedTestDispatcher()
)
viewModel = MainViewModel(repository)
}
@Test
fun `Get Stories Success`() = runTest {
repository.login("[email protected]", "gabbustacia")
advanceUntilIdle()
viewModel.getSession()
val differ = AsyncPagingDataDiffer(
StoryAdapter.DIFF,
listUpdateCallback,
)
val token = repository.getSession().asLiveData().getOrAwaitValue(10).token
val remote = ApiConfig.getApiService().getStories("Bearer $token", 1, 10)
val pagingData = viewModel.story.getOrAwaitValue(100)
differ.submitData(pagingData)
Assert.assertNotNull(differ.snapshot())
}
}
But the problem is, the test failed on differ.submitData due to coroutine didn't finished even after 10 Seconds. Why is that? I tried to create a fake list and insert into the differ, and everything works fine.
I already tried using another list and seems to work just fine, but when i want to test the paging itself, it doesn't works.