Billy Newman
06/12/2023, 8:27 PMBilly Newman
06/12/2023, 8:29 PM// 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 { item ->
ListItem(item)
}
.insertSeparators { item1: ListItem?, item2: ListItem? ->
// logic I want to test
}
}.cachedIn(viewModelScope)
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
}
This follows the example laid out by android with the exception of using mocks rather than extending the viewmodel. I have verified that the mock is called and the flow is created. However when I grab the snapshot the list of items from the flow is empty.