I have the same coEvery
working without issue on PagingDataSource
unit test but got exception while trying to write test against viewModel :
class PostViewModelTest {
private val getPostUseCase : GetPostUseCase = mockk()
private val viewModel = PostViewModel(getPostUseCase)
@OptIn(ExperimentalCoroutinesApi::class)
@Before
fun setup() {
Dispatchers.setMain(Dispatchers.Unconfined)
}
@OptIn(ExperimentalCoroutinesApi::class)
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun test_items_contain_one_to_ten() = runTest {
// Get the Flow of PagingData from the ViewModel under test
// Given
val expectedPostsList = List(23) {
DomainModelFactory.getDefaultPostModel(UUID.randomUUID().toString())
}
coEvery { getPostUseCase.invoke(0) } returns ResultOf.Success(expectedPostsList)
mockkStatic(Log::class)
every { Log.isLoggable(any(), any()) } returns true
every { Log.d(any(), any()) } returns 0
val items: Flow<PagingData<PostModel>> = viewModel.uiState
val itemsSnapshot: List<PostModel> = items.asSnapshot {
// Scroll to the 50th item in the list. This will also suspend till
// the prefetch requirement is met if there's one.
// It also suspends until all loading is complete.
scrollTo(index = 50)
}
// With the asSnapshot complete, you can now verify that the snapshot
// has the expected values
assertEquals(
(0..50).map(Int::toString),
itemsSnapshot
)
}
}