【发布时间】:2022-01-10 12:05:03
【问题描述】:
有人可以建议如何在函数中协程延迟背后的代码行上断言。我无法使用注入的dispatchers 和使用runBlockingTest 来做到这一点。我还更新了我的项目依赖项并尝试使用较新的 runTest 无济于事。
请有人建议。
代码示例:
val liveData1 = MutableLiveData(false)
fun foo() {
doTheThing(liveData1, {lambda1(liveData1)})
}
fun doTheThing(liveData1: LiveData<Boolean>, f1: () -> Unit) {
if (!liveData1.value) {
f1()
}
}
fun lambda1(liveData1: LiveData<Boolean>) {
viewModelScope.launch(dispatchers.main) {
delay(1000)
liveData1.postValue(true)
delay(1000)
liveData1.postValue(false)
}
}
测试示例:
@ExperimentalCoroutinesApi
@Test `test doTheThing`() = runBlockingTest{
val subject = MyClass(TestCoroutineDispatchers())
val observer1 = subject.liveData1.test()
observers1.assertValueHistory(false)
subject.foo()
observers1.assertValueHistory(false, true, false) // fails here stating should have history [false]!=[false, true, false]
}
我已经检查过了,如果我将延迟设置为 0,那么我的断言是正确的。我已经通过调试器,测试总是将代码运行到第一个延迟,但永远不会在延迟之后到达代码。
LiveData 测试辅助函数:
fun <T> LiveData<T>.test(): TestObserver<T> = TestObserver.test(this)
********
public TestObserver<T> assertValueHistory(T... values) {
List<T> mValueHistory = valueHistory();
int size = mValueHistory.size();
if (size != values.length) {
throw fail("Value count differs; expected: " + values.length + " " + Arrays.toString(values)
+ " but was: " + size + " " + this.valueHistory);
}
for (int valueIndex = 0; valueIndex < size; valueIndex++) {
T historyItem = mValueHistory.get(valueIndex);
T expectedItem = values[valueIndex];
if (notEquals(expectedItem, historyItem)) {
throw fail("Values at position " + valueIndex + " differ; expected: " + valueAndClass(expectedItem) + " but was: " + valueAndClass(historyItem));
}
}
return this;
}
【问题讨论】:
标签: android kotlin delay kotlin-coroutines