LiveData测试:如何跟踪值变化的顺序?

And*_*sev 5 android unit-testing kotlin android-livedata

我通过官方教程学习LiveData测试。我想了解如何验证测试中更改 LiveData 值的顺序。我将这样的代码添加到被测试的类(TasksViewModel)中:

val processing = MutableLiveData <Boolean> (false)

fun someLongProcessing () {
    processing.value = true
    viewModelScope.launch (Dispatchers.IO) {
        sleep (10000)
        processing.value = false
    }
}
Run Code Online (Sandbox Code Playgroud)

我想检查processing首先评估为false然后评估为true。我将这段代码添加到测试中:

    tasksViewModel.someLongProcessing ()
    var processing = tasksViewModel.processing.getOrAwaitValue ()
    assertTrue(processing)
    processing = tasksViewModel.processing.getOrAwaitValue()
    assertFalse(processing)
Run Code Online (Sandbox Code Playgroud)

但是第二次调用getOrAwaitValue总是返回true,尽管它期望返回下一个 LiveData 值 - falsegetOrAwaitValue功能代码:

@VisibleForTesting (otherwise = VisibleForTesting.NONE)
fun <T> LiveData <T> .getOrAwaitValue (
        time: Long = 2,
        timeUnit: TimeUnit = TimeUnit.SECONDS,
        afterObserve: () -> Unit = {}
): T {
    var data: T? = null
    val latch = CountDownLatch (1)
    val observer = object: Observer <T> {
        override fun onChanged (o: T?) {
            data = o
            latch.countDown ()
            this@getOrAwaitValue.removeObserver (this)
        }
    }
    this.observeForever (observer)

    try {
        afterObserve.invoke ()

        // Don't wait indefinitely if the LiveData is not set.
        if (! latch.await (time, timeUnit)) {
            throw TimeoutException ("LiveData value was never set.")
        }

    } finally {
        this.removeObserver (observer)
    }

    @Suppress ("UNCHECKED_CAST")
    return data as T
}
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?也许还有另一种方法来测试 LiveData 值更改的顺序?