mercredi 2 décembre 2020

Get livedata latest value while testing view model

I'm trying to unit test my viewmodel:

private val loginRepository: LoginRepository = LoginRepository()
    private val _loginSuccess = MutableLiveData<Resource<String>>()
    val loginSuccess : LiveData<Resource<String>>
        get() = _loginSuccess

fun login(credentials : RequestLogin){
    _loginSuccess.value = Resource.loading()
    viewModelScope.launch {
        _loginSuccess.postValue(loginRepository.login(credentials))
    }

With this:

@Test
fun login_success(){
    val loginRequest = RequestLogin("username", "test")
    val app:Application = ApplicationProvider.getApplicationContext()
    PreferencesHelper.init(app)
    val viewModel = LoginViewModel(app)
    viewModel.loginSuccess.observeForever(dataObserver)

    runBlocking {
        viewModel.login(loginRequest)
        assertEquals(viewModel.loginSuccess.getOrAwaitValue(), Resource.success("OK"))
    }

    viewModel.loginSuccess.removeObserver(dataObserver)
}

But everytime i'm getting just the first value of the liveData object Resource.loading() instead of the one obtained with the postValue method.

How can i ignore the result of the first liveData update and just get the final one?

Aucun commentaire:

Enregistrer un commentaire