I am running into an issue trying to mock paging data coming from a repository. Here is the portion in my viewmodel I would like to test:
// watch for filter to change, on charge reset the paging query
val items = filterParameter.switchMap { filter ->
Pager(
config = PagingConfig(pageSize = 20),
initialKey = null,
pagingSourceFactory = {
repository.observeItems(filter)
}
).liveData
}.asFlow().map { pagingData ->
pagingData
.map {
ListItem(it)
}
.insertSeparators { item1: ListItem?, item2: ListItem? ->
// logic I want to test
}
}.cachedIn(viewModelScope)
And my test:
@Test
fun testTransformation() = runTest {
val repository = mock<MyRepository>()
`when`(repository.observeItems(Mockito.any()))
.thenAnswer {
val flow = flowOf(
listOf(
Item(
id = "1",
date = Date()
)
)
)
val pagingSourceFactory = flow.asPagingSourceFactory(coroutineScope = this)
pagingSourceFactory()
}
val viewModel = MyViewModel(
repository = repository,
)
val items: Flow<PagingData<ListItem>> = viewModel.items
val snapshot: List<ListItem> = items.asSnapshot() {}
Assert.assertEquals(1, snapshot.size) // fails as zero items are in the snapshot
}
I have verified that when running the test, the pager is setup in the viewmodel, and the mock flow is called. However I am not seeing the mocked data come back. Any ideas?
Demo android project on GitHub here: https://github.com/newmanw/android-paging-test