gpt4 book ai didi

Android 检测测试在测试使用 RoomDatabase.withTransaction 的挂起函数时卡住

转载 作者:行者123 更新时间:2023-12-03 23:47:35 24 4
gpt4 key购买 nike

我正在尝试测试以下 LocalDataSource 函数, NameLocalData.methodThatFreezes 功能,但它卡住。我该如何解决这个问题?或者我该如何以另一种方式对其进行测试?

待测类

class NameLocalData(private val roomDatabase: RoomDatabase) : NameLocalDataSource {

override suspend fun methodThatFreezes(someParameter: Something): Something {
roomDatabase.withTransaction {
try {
// calling room DAO methods here
} catch(e: SQLiteConstraintException) {
// ...
}
return something
}
}
}

测试类
@MediumTest
@RunWith(AndroidJUnit4::class)
class NameLocalDataTest {
private lateinit var nameLocalData: NameLocalData

// creates a Room database in memory
@get:Rule
var roomDatabaseRule = RoomDatabaseRule()

@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()

@Before
fun setup() = runBlockingTest {
initializesSomeData()
nameLocalData = NameLocalData(roomDatabaseRule.db)
}

@Test
fun methodThatFreezes() = runBlockingTest {
nameLocalData.methodThatFreezes // test freezes
}

// ... others NameLocalDataTest tests where those functions been tested does not use
// roomDatabase.withTransaction { }
}

Gradle 的文件配置
espresso_version = '3.2.0'
kotlin_coroutines_version = '1.3.3'
room_version = '2.2.5'

test_arch_core_testing = '2.1.0'
test_ext_junit_version = '1.1.1'
test_roboletric = '4.3.1'
test_runner_version = '1.2.0'

androidTestImplementation "androidx.arch.core:core-testing:$test_arch_core_testing"
androidTestImplementation "androidx.test.espresso:espresso-core:$espresso_version"
androidTestImplementation "androidx.test.ext:junit:$test_ext_junit_version"
androidTestImplementation "androidx.test:rules:$test_runner_version"
androidTestImplementation "androidx.test:runner:$test_runner_version"
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlin_coroutines_version"

最佳答案

上次我为 Room 数据库编写测试时,我只是简单地使用了 runBlock它对我有用......
你能看看this sample并检查它是否也适合您?

编辑:
行动!我错过了这部分......我试过这个(在同一个样本中):

  • 我使用 @Transaction 在我的 DAO 中定义了一个虚拟函数
  • @Transaction
    suspend fun quickInsert(book: Book) {
    save(book)
    delete(book)
    }
  • 我认为这是问题的关键。添加 setTransactionExecutor到您的数据库实例化。
  • appDatabase = Room.inMemoryDatabaseBuilder(
    InstrumentationRegistry.getInstrumentation().context,
    AppDatabase::class.java
    ).setTransactionExecutor(Executors.newSingleThreadExecutor())
    .build()
  • 最后,使用 runBlocking 进行测试。
  • @Test
    fun dummyTest() = runBlocking {
    val dao = appDatabase.bookDao();
    val id = dummyBook.id

    dao.quickInsert(dummyBook)

    val book = dao.bookById(id).first()
    assertNull(book)
    }

    this question .

    关于Android 检测测试在测试使用 RoomDatabase.withTransaction 的挂起函数时卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61648948/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com