Skip to content

Instantly share code, notes, and snippets.

@nhphong
Created May 8, 2020 02:43
Show Gist options
  • Save nhphong/3303cd5cc8da92beba37bfc09ddcc55c to your computer and use it in GitHub Desktop.
Save nhphong/3303cd5cc8da92beba37bfc09ddcc55c to your computer and use it in GitHub Desktop.
package com.ea.credgreen.testutils
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import com.ea.credgreen.assertWithTimeout
internal class DataRecorder<T> {
private val mutex = Any()
private val _values = mutableListOf<T?>()
fun add(value: T?) = synchronized(mutex) {
_values += value
}
fun assertValues(timeout: Long = 1000L, expectedValues: List<T?>) {
assertWithTimeout(timeout) {
_values == expectedValues
}
}
}
internal fun <T> LiveData<T>.assertEmit(vararg expected: T?): AssertEmission<T> {
val recorder = DataRecorder<T>()
val observer = Observer<T> { recorder.add(it) }
observeForever(observer)
return AssertEmission(this, observer, recorder, expected.asList())
}
internal fun <T> LiveData<T>.assertNoEmit(): AssertEmission<T> {
return assertEmit()
}
internal data class AssertEmission<T>(
private val source: LiveData<T>,
private val observer: Observer<T>,
private val recorder: DataRecorder<T>,
private val emittedItems: List<T?>
) {
infix fun asAResultOf(block: () -> Unit) {
try {
block()
assertValues()
} finally {
cleanUp()
}
}
infix fun afterExecuting(block: () -> Unit) {
asAResultOf(block)
}
fun assertValues() {
recorder.assertValues(expectedValues = emittedItems)
}
fun cleanUp() {
source.removeObserver(observer)
}
}
internal infix fun List<AssertEmission<*>>.asAResultOf(block: () -> Unit) {
try {
block()
forEach { it.assertValues() }
} finally {
forEach { it.cleanUp() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment