android - 在 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 上工作,而不是在调用它们的库上工作吗?
解决方案
我也在使用 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())
}
}
推荐阅读
- python - 谁能告诉我这个 HackerRank 问题的逻辑问题?(重复字符串,描述中的链接)
- r - 使用 R 将多列数据帧转换为长 3 列数据帧
- node.js - 通过 markdown-pdf 将最近 git commit 的哈希添加到 pdf 的页脚
- ios - 为什么发生 .resignFirstResponder 时没有执行 Currency Formatter
- java - 在 Eclipse 中调试以前调试的行
- ios - Flutter ios MobileFFmpegConfig.h 未找到
- vue.js - 将 v-select 与 vuex 连接:问题 [object object]
- c# - 二进制数组在 C# 中将映射缩减为矩形
- highcharts - 如何显示系列的两个值 [例如:“395 — (27%)”]?
- avaloniaui - 类似于 Avalonia UI 中的抽象 Adorner (wpf) 类?