Created
October 15, 2019 07:32
-
-
Save Marchuck/c64e72d783880e9fa481f3da3acbe0a7 to your computer and use it in GitHub Desktop.
testing LiveData
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.lifecycle.LiveData | |
internal fun <T> LiveData<T>.observeEvents() = TestObserver<T>().also { observeForever(it) } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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