Код: Выделить всё
class HomeViewModel(
private val repository: CitiesRepository,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
): ViewModel() {
private val _uiState = MutableStateFlow(HomeState())
val uiState = _uiState.asStateFlow()
init {
println("in init block") // Log
fetchData()
}
private fun fetchData() {
viewModelScope.launch(dispatcher) {
println("Corrutina iniciada") // Log
_uiState.update { _uiState.value.copy(isLoading = true) }
val data = repository.fetchDummyData()
_uiState.update { _uiState.value.copy(data = data, isLoading = false) }
println("Corrutina finalizada") // Log
}
}
Код: Выделить всё
@OptIn(ExperimentalCoroutinesApi::class)
class HomeViewModelTest {
private lateinit var viewModel: HomeViewModel
private val repository: CitiesRepository = mockk()
private val testDispatcher = StandardTestDispatcher()
private val scope = TestScope(testDispatcher)
@Before
fun setUp() {
coEvery { repository.fetchDummyData() } returns listOf(
"New York",
"Los Angeles",
"San Francisco"
)
Dispatchers.setMain(testDispatcher)
viewModel = HomeViewModel(repository, dispatcher = testDispatcher)
}
это мой результат println
Код: Выделить всё
> in init block
> Corrutina iniciada
> Corrutina finalizada
> HomeViewModelTest -> initial state is loading
при первом утверждении происходит сбой
Код: Выделить всё
@Test
fun `ViewModel initial state is loading`() = scope.runTest {
println("HomeViewModelTest -> initial state is loading")
assert(HomeState() == viewModel.uiState.value)
assertTrue(viewModel.uiState.value.isLoading)
// Esperar a que fetchCities se complete
println("HomeViewModelTest -> avanzar en corutina")
testDispatcher.scheduler.advanceUntilIdle()
Я знаю, что есть турбина для подобного теста, но хочу знать, что не так в моем тесте.
Подробнее здесь: https://stackoverflow.com/questions/790 ... d-function