@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun `view model test`() = runTest {
val employees = EmployeeResponse(listOf())
`when`(employeeRepo.getEmployees()).thenReturn(employees)
`when`(employeeMapper.mapToState(anyList())).thenReturn(emptyList())
val testDispatcher = StandardTestDispatcher(testScheduler)
Dispatchers.setMain(testDispatcher)
viewModel = EmployeeViewModel(employeeRepo, employeeMapper)
viewModel.getEmployees()
advanceUntilIdle()
Assert.assertTrue(viewModel.uiState.value is EmployeeViewModel.EmployeeState.Success)
verify(employeeRepo, times(1)).getEmployees()
Dispatchers.resetMain()
}
The assertion is failing because, assertion statement is executing before _uiState
is executed. How to fix it?
View model code is below
fun getEmployees() {
val errorHandler = CoroutineExceptionHandler { _, error ->
handleError(error)
}
viewModelScope.launch(errorHandler) {
val employees = withContext(Dispatchers.IO) {
employeeRepo.getEmployees()
}
_uiState.value = EmployeeState.Success(employeeMapper.mapToState(employees.employees))
}
}
You need to sign in to view this answers