首页 > 解决方案 > 在 junit 测试中使用 InstantTaskExecutorRule 会导致 java.lang.RuntimeException

问题描述

我正在对一个使用RoomDatabase. RoomDatabase对自身进行了单元测试,InstantTaskExecutorRule以便LiveData可以立即进行更新:

@Rule public TestRule rule = new InstantTaskExecutorRule();

这很好用。但是,在对调用数据库的库进行单元测试时,使用相同的规则会导致测试抛出异常:

java.lang.RuntimeException: Exception while computing database live data.
...
Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.

有什么理由InstantTaskExecutorRule可以在底层数据库 DAO 上工作,而不是在调用它们的库上工作吗?

标签: androidandroid-roomandroid-testingandroid-livedata

解决方案


我也在使用 Robolectric 对 RoomDatabase 进行单元测试,并且在使用时出现同样的错误

@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()

我只是删除了它,并且在我的测试中使用了 runBlocking{ ... },如下例所示:

@Test
@Throws(Exception::class)
fun `test insert and retrieve text`() {
    runBlocking {
        dao.insertText("some text")
        assertEquals("some text",dao.getText())
    }
}

推荐阅读