Skip to content

Instantly share code, notes, and snippets.

@Marchuck
Created October 15, 2019 07:32
Show Gist options
  • Save Marchuck/c64e72d783880e9fa481f3da3acbe0a7 to your computer and use it in GitHub Desktop.
Save Marchuck/c64e72d783880e9fa481f3da3acbe0a7 to your computer and use it in GitHub Desktop.
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