LiveData's Transformations.map not being triggered in, and only in, Unit Tests

Viewed 269

I have a ViewModel like this one:

class MyViewModel {
    val title = MutableLiveData<String>()
    val onTitleError: LiveData<Int?> = Transformations.map(title, this::validateTitle)
}

The problem is when executing during Unit Tests Transformations.map is never triggered by a title value change. As example:

val viewModel = MyViewModel()
viewModel.title.value = "123"

Assert.assertEquals(viewModel.onTitleError.value, R.string.myError)

I'm using this rule for LiveData tests:

@Rule
var liveDataRule: TestRule = InstantTaskExecutorRule()

When executing during Instrumented Tests, or normal running, everything works just fine.

Just exemplifying @ianhanniballake answer, i just added viewModel.onTitleError.observeForever { }, then above snippet should look like this:

val viewModel = MyViewModel()

viewModel.onTitleError.observeForever { }
viewModel.title.value = "123"

Assert.assertEquals(viewModel.onTitleError.value, R.string.myError)
1 Answers

You need to observe your onTitleError LiveData to have it populate its value.

Related