使用Kotlin协程和流量测试DAO室的方法

问题描述 投票:0回答:1

我正在尝试从LiveData迁移到我的Room Dao中的Flow。应用程序运行正常,但测试行为存在问题。当我运行测试时,它会不确定地启动和运行。我也尝试使用kotlinx.coroutines.test runBlockingTest,但是像“ here”这样的“此工作尚未完成”问题。有人可以指出正确的方向如何测试CoresDao的行为吗?

@Dao
interface CoresDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertCores(cores: List<Core>)

    @Transaction
    suspend fun replaceCoresData(cores: List<Core>) {
        deleteAllCores()
        insertCores(cores)
    }

    @Query("SELECT * FROM cores_table")
    fun getAllCores(): Flow<List<Core>>

    @Query("DELETE FROM cores_table")
    suspend fun deleteAllCores()
}

@RunWith(AndroidJUnit4::class)
class CoresDaoTest {

    private lateinit var database: SpaceDatabase
    private lateinit var coresDao: CoresDao

    private val testDispatcher = TestCoroutineDispatcher()

    private val testCoresList = listOf(core2, core3, core1)

    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    @Before
    fun setup() {
        Dispatchers.setMain(testDispatcher)

        val context = InstrumentationRegistry.getInstrumentation().targetContext
        database = Room.inMemoryDatabaseBuilder(context, SpaceDatabase::class.java).build()
        coresDao = database.coresDao()
    }

    @After
    fun cleanup() {
        database.close()

        Dispatchers.resetMain()
        testDispatcher.cleanupTestCoroutines()
    }

    @Test
    fun testGetAllCores(): Unit = runBlocking {
        withContext(Dispatchers.Main) {
            runBlocking { coresDao.insertCores(testCoresList) }

            val coresList = mutableListOf<Core>()
            coresDao.getAllCores().collect { cores -> coresList.addAll(cores) }

            assertThat(coresList.size, equalTo(testCoresList.size))
        }
    }
}
android unit-testing android-room kotlin-coroutines kotlinx.coroutines.flow
1个回答
0
投票

由于您已经在使用TestCoroutineDispatcher,因此在您的示例中,使用runBlockingTest不会执行任何操作。收集后,您必须cancel Flow或启动scopeFlow

编辑:可以找到此类规则的示例here

© www.soinside.com 2019 - 2024. All rights reserved.