https://kotlinlang.org logo
j

Jitendra

07/07/2023, 7:14 AM
I am very new in Unit testing , i am trying to test my flow using Turbine library, it is not emitting all value, here is my test
Copy code
@Test
fun `send function should emit Loading and Content states`() = runTest {
    // Arrange
    val userProfile = UserProfile(login = "test_login")
    val contentState = UiState.Content(userProfile)


    coEvery {
        fakeRepository.getDetail(any())
    } returns userProfile


    // Act
    viewModel.send(userProfile.login!!)


    // Assert
    testScheduler.advanceUntilIdle()
    viewModel.uiState.test {
        assertEquals(UiState.Loading, awaitItem())
        assertEquals(contentState, awaitItem())
        cancelAndIgnoreRemainingEvents()
    }
}
and ViewModel is here, keep failing with reason Expected UiState$Loading Actual :Content
Copy code
fun send(login: String) =
    viewModelScope.launch(dispatchers.main) {
        flow {
            emit(UiState.Loading)
            val mResponse = userRepository.getDetail(login = login)
            emit(UiState.Content(mResponse))
        }.catch {
            UiState.Error(it.message.toString())
            it.printStackTrace()
        }.flowOn(dispatchers.main).collect {
            _uiState.value = it
        }
    }
I need help
d

Daniel Weidensdörfer

07/07/2023, 5:32 PM
I suggest to remove
advanceUntilIdle
and if that doesnt help, also put the
viewModel.send()
into the
viewmodel.uiState.test {}
block. Are you setting the main dispatcher to a test dispatcher at the beginning of your tests?