相关疑难解决方法(0)

单元测试室和LiveData

我目前正在使用新的Android架构组件开发应用程序.具体来说,我正在实现一个房间数据库,LiveData它在其中一个查询上返回一个对象.插入和查询按预期工作,但是我在使用单元测试测试查询方法时遇到问题.

这是我试图测试的DAO:

NotificationDao.kt

@Dao
interface NotificationDao {

@Insert
fun insertNotifications(vararg notifications: Notification): List<Long>

@Query("SELECT * FROM notifications")
fun getNotifications(): LiveData<List<Notification>>
Run Code Online (Sandbox Code Playgroud)

}

正如你所知,查询函数返回一个LiveData对象,如果我将其更改为a List,Cursor或者基本上是什么,然后我得到预期结果,即插入数据库中的数据.

问题是,下面的测试将始终失败,因为value该的LiveData对象始终是null:

NotificationDaoTest.kt

lateinit var db: SosafeDatabase
lateinit var notificationDao: NotificationDao

@Before
fun setUp() {
    val context = InstrumentationRegistry.getTargetContext()
    db = Room.inMemoryDatabaseBuilder(context, SosafeDatabase::class.java).build()
    notificationDao = db.notificationDao()
}

@After
@Throws(IOException::class)
fun tearDown() {
    db.close()
}

@Test
fun getNotifications_IfNotificationsInserted_ReturnsAListOfNotifications() {
    val NUMBER_OF_NOTIFICATIONS = 5
    val …
Run Code Online (Sandbox Code Playgroud)

android unit-testing kotlin android-room android-architecture-components

44
推荐指数
5
解决办法
1万
查看次数

使用 Room @Transaction 函数时,Android 仪器测试不会运行到结束

我正在使用 AS 3.4.1 和运行 Android 9 的模拟器进行测试。

当我Room Dao Function annotated with @Transaction在其中使用 a 时,以下测试将无法运行。

class RecurrenceManagerTest : DatabaseTest() {

    @Rule
    @JvmField
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    var recurringEntryId: Long = -1

    @Before
    override fun setup() {
        super.setup() // only initialized the db

        val recurringEntry = RecurringEntry(
            recurrence = Recurrence(DATE.toEpochMilli(), Recurrence.DAILY)
        )

        recurringEntryId = runBlocking { db.recurringEntryDao().insert(recurringEntry) }

        val recurringBookEntry = BookEntry.create(
            title = TITLE,
            date = DATE,
            value = VALUE,
            isPaid = IS_PAID,
            notes = NOTES,
            entryType = …
Run Code Online (Sandbox Code Playgroud)

android kotlin android-room android-architecture-components kotlin-coroutines

7
推荐指数
2
解决办法
1314
查看次数