无法在后台线程上调用 observeForever

Cannot invoke observeForever on a background thread

我一直在使用 中描述的 observeForever() 方法来测试 Room 和 LiveData 一段时间,它运行得非常完美。但是当我更改为 Android Studio 3.2(或者是否是 androidx 重构,不确定)时,该方法突然停止工作,抛出一个

java.lang.IllegalStateException: Cannot invoke observeForever on a background thread

我们该如何解决这个问题?

我通过添加规则 InstantTaskExecutorRule 解决了这个问题。根据 docs 它将

A JUnit Test Rule that swaps the background executor used by the Architecture Components with a different one which executes each task synchronously.

所以需要添加

@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()

测试 class 它是否有效。 Java 相当于

@Rule
public InstantTaskExecutorRule instantTaskExecutorRule = new InstantTaskExecutorRule();

您还需要添加

androidTestImplementation "androidx.arch.core:core-testing:2.0.0"

到您的模型 build.gradle 依赖项。

作为这种方法的初学者,接受的答案对我来说有点模糊。所以只是想解释一下

将此添加到您的 build.gradle

androidTestImplementation "androidx.arch.core:core-testing:2.0.0

现在我们需要在测试功能上添加rule。假设我有一个测试函数 writeAndReadCategory 然后它在 kotlin

中看起来像这样
    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()
    @Test
    fun writeAndReadCategory() {
        ....
    }