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)
You need to observe
your onTitleError
LiveData to have it populate its value
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.