我正在为Android Room数据库编写一个仪器化测试,但不幸的是,由于在主线程上执行了该操作,该测试崩溃了:
java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
在配置测试数据库时,我打开设置allowMainThreadQueries()
以明确防止此问题。
示例代码:
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.runner.AndroidJUnit4
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
import kotlin.test.assertTrue
@RunWith(AndroidJUnit4::class)
class NewsDatabaseTest {
private lateinit var cachedNewsDao: CachedNewsDao
private lateinit var db: NewsDatabase
@Before
fun setUp() {
val context = ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder(context, NewsDatabase::class.java)
.allowMainThreadQueries()
.build()
cachedNewsDao = db.cachedNewsDao()
}
@After
@Throws(IOException::class)
fun closeDb() {
db.close()
}
@Test
fun ensure_dao_has_items() {
val newsList: List<CachedNews> = cachedNewsDao.getNews()
assertTrue { newsList.isEmpty() }
}
}
在唯一的测试方法中,堆栈跟踪最初指向空行。您会看到第一行是我在setUp
中明确关闭的行。
at androidx.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:267)
at androidx.room.RoomDatabase.query(RoomDatabase.java:323)
at androidx.room.util.DBUtil.query(DBUtil.java:83)
at com.package.feature.news.cache.CachedNewsDao_Impl.getNews(CachedNewsDao_Impl.java:97)
at com.package.feature.news.cache.NewsDatabaseTest.ensure_dao_has_items(NewsDatabaseTest.kt:44)
为什么Room忽略了allow主线程查询配置?
我找到了一种解决方法,可以通过以下命令行运行测试:./gradlew connectedAndroidTest
。