Hi, I am trying to write a test for my android app...
# coroutines
r
Hi, I am trying to write a test for my android app but I can’t get it to work. I never receive the ViewState.Info state. Instead I only get the initial Loading state. The code is in the reply thread.
Copy code
@ExperimentalCoroutinesApi
@ExperimentalTime
internal class IntegrationTest : BaseViewModelTest() {

    @Test
    fun `my first test`() = coroutineDispatcher.runBlockingTest {
        val viewModel = MyViewModel(MyRepo(), coroutineDispatcher)

        pauseDispatcher()

        viewModel.handleIntent()

        viewModel.state.test {
            val first = expectItem() as <http://ViewState.Info|ViewState.Info>
            assertEquals(<http://ViewState.Info::class|ViewState.Info::class>, first::class)
            cancelAndConsumeRemainingEvents()
        }

        resumeDispatcher()
    }
}

class MyViewModel(
    private val repo: MyRepo,
    private val dispatcher: CoroutineDispatcher
) : ViewModel() {

    private val _state = MutableStateFlow<ViewState>(ViewState.Loading)
    val state: StateFlow<ViewState>
        get() = _state

    fun handleIntent() {
        viewModelScope.launch() {
            withContext(dispatcher) {
                val name = repo.getUser()
                _state.emit(<http://ViewState.Info|ViewState.Info>(name))
            }
        }
    }
}

sealed class ViewState {
    object Loading : ViewState()
    data class Info(val name: String) : ViewState()
}

class MyRepo {

    suspend fun getUser(): String {
        delay(1000L)
        return "John"
    }
}