Created
December 7, 2018 07:00
-
-
Save afollestad/f358cdd3a4b146a0158e0f3e1f89b7c6 to your computer and use it in GitHub Desktop.
Observe LiveData in a test like you can with Rx test subscribers.
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
/** @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