Created
May 8, 2020 02:43
-
-
Save nhphong/3303cd5cc8da92beba37bfc09ddcc55c to your computer and use it in GitHub Desktop.
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
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