Skip to content

Instantly share code, notes, and snippets.

@afollestad
Created December 7, 2018 07:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afollestad/f358cdd3a4b146a0158e0f3e1f89b7c6 to your computer and use it in GitHub Desktop.
Save afollestad/f358cdd3a4b146a0158e0f3e1f89b7c6 to your computer and use it in GitHub Desktop.
Observe LiveData in a test like you can with Rx test subscribers.
/** @author Aidan Follestad (@afollestad) */
class TestLiveData<T>(data: LiveData<T>) {
private val receivedValues = mutableListOf<T>()
private val observer = Observer<T> { emission ->
emission?.let { receivedValues.add(it) }
}
init {
data.observeForever(observer)
}
fun assertNoValues() {
if (receivedValues.isNotEmpty()) {
throw AssertionError("Expected no values, but got: $receivedValues")
}
}
fun assertValues(vararg assertValues: T) {
val assertList = assertValues.toList()
if (!assertList.contentEquals(receivedValues)) {
throw AssertionError("Expected $assertList\n\t\tBut got: $receivedValues")
}
receivedValues.clear()
}
@CheckResult fun values(): List<T> = receivedValues
private fun List<T>.contentEquals(other: List<T>): Boolean {
if (this.size != other.size) {
return false
}
for ((index, value) in this.withIndex()) {
if (other[index] != value) {
return false
}
}
return true
}
}
@CheckResult fun <T> LiveData<T>.test() = TestLiveData(this)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment