Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
testing LiveData
ExampleTest{
@BeforeEach
fun setUp() {
viewModel = SomeViewModel(...)
filtersObserver = viewModel.filtersLiveData.observeEvents()
}
@Test fun `test 1`(){
val expected = arrayListOf<Any>()
viewModel.requestSomeArrayList(Any())
assertEquals(filtersObserver.firstValue(), expected)
}
@AfterEach
fun tearDown() {
viewModel.filtersLiveData.removeObserver(filtersObserver)
}
}
import androidx.lifecycle.LiveData
internal fun <T> LiveData<T>.observeEvents() = TestObserver<T>().also { observeForever(it) }
import androidx.lifecycle.Observer
internal class TestObserver<T> : Observer<T> {
val observedValues = mutableListOf<T?>()
override fun onChanged(value: T?) {
observedValues.add(value)
}
fun firstValue() = observedValues.first()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment