Skip to content

Instantly share code, notes, and snippets.

@shredderskelton
Created February 19, 2021 19:06
Show Gist options
  • Save shredderskelton/a015cb051578d11096b02008b7d4bc65 to your computer and use it in GitHub Desktop.
Save shredderskelton/a015cb051578d11096b02008b7d4bc65 to your computer and use it in GitHub Desktop.
LiveDataTestObserver
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.asLiveData
import kotlinx.coroutines.flow.Flow
class LiveDataTestObserver<T> : Observer<T> {
val observedValues = mutableListOf<T>()
override fun onChanged(value: T) {
observedValues.add(value)
}
}
fun <T> LiveData<T>.test() = LiveDataTestObserver<T>()
.also { observeForever(it) }
// Now we can do something like this:
@Test
fun `history pagination`() {
coroutinesTestRule.testDispatcher.runBlockingTest {
// Given
val result = underTest.myLiveDataProperty.test()
// When
underTest.load()
underTest.loadMore()
underTest.loadMoreEvenMore()
// Then
assertThat(result.observedValues).containsExactly(
listOf(record),
listOf(record, record2),
listOf(record, record2, record3),
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment