使用 LiveData、协程和事务测试 Android Room

Mar*_*lka 16 testing android kotlin android-room kotlin-coroutines

我想测试我的数据库层,但我发现自己陷入了 catch-22 类型的情况。

测试用例由两部分组成:

  • 保存一些实体
  • 加载实体并断言数据库映射按预期工作

简而言之,问题在于:

  • Insert是一个suspend方法,这意味着它需要运行runBlocking{}
  • Query返回一个LiveData结果,这也是异步的。因此需要观察。有这个SO question 解释了如何做到这一点。
  • 但是,为了根据上述链接观察 LiveData,我必须使用InstantTaskExecutorRule. (否则我得到java.lang.IllegalStateException: Cannot invoke observeForever on a background thread.
  • 这适用于大多数情况,但不适用于带@Transaction注释的 DAO 方法。测试永远不会结束。我认为它在等待某个事务线程时陷入僵局。
  • 删除InstantTaskExecutorRule让 Transaction-Insert 方法完成,但随后我无法断言其结果,因为我需要规则才能观察数据。

详细说明

我的Dao课是这样的:

@Dao
interface GameDao {
    @Query("SELECT * FROM game")
    fun getAll(): LiveData<List<Game>>

    @Insert
    suspend fun insert(game: Game): Long

    @Insert
    suspend fun insertRound(round: RoundRoom)

    @Transaction
    suspend fun insertGameAndRounds(game: Game, rounds: List<RoundRoom>) {
        val gameId = insert(game)
        rounds.onEach {
            it.gameId = gameId
        }

        rounds.forEach {
            insertRound(it)
        }
    }
Run Code Online (Sandbox Code Playgroud)

测试用例是:

@RunWith(AndroidJUnit4::class)
class RoomTest {
    private lateinit var gameDao: GameDao
    private lateinit var db: AppDatabase

    @get:Rule
    val instantTaskExecutorRule = InstantTaskExecutorRule()

    @Before
    fun createDb() {
        val context = ApplicationProvider.getApplicationContext<Context>()
        db = Room.inMemoryDatabaseBuilder(
            context, AppDatabase::class.java
        ).build()
        gameDao = db.gameDao()
    }

    @Test
    @Throws(Exception::class)
    fun storeAndReadGame() {
        val game = Game(...)

        runBlocking {
            gameDao.insert(game)
        }

        val allGames = gameDao.getAll()

        // the .getValueBlocking cannot be run on the background thread - needs the InstantTaskExecutorRule
        val result = allGames.getValueBlocking() ?: throw InvalidObjectException("null returned as games")

        // some assertions about the result here
    }

    @Test
    fun storeAndReadGameLinkedWithRound() {
        val game = Game(...)

        val rounds = listOf(
            Round(...),
            Round(...),
            Round(...)
        )

        runBlocking {
            // This is where the execution freezes when InstantTaskExecutorRule is used
            gameDao.insertGameAndRounds(game, rounds)
        }

        // retrieve the data, assert on it, etc
    }
}

Run Code Online (Sandbox Code Playgroud)

getValueBlocking是一个扩展功能LiveData,几乎从上面的链接复制粘贴

fun <T> LiveData<T>.getValueBlocking(): T? {
    var value: T? = null
    val latch = CountDownLatch(1)

    val observer = Observer<T> { t ->
        value = t
        latch.countDown()
    }

    observeForever(observer)

    latch.await(2, TimeUnit.SECONDS)
    return value
}
Run Code Online (Sandbox Code Playgroud)

测试这种情况的正确方法是什么?我在开发数据库映射层时需要这些类型的测试,以确保一切都按我的预期工作。

Mar*_*lka 9

这个问题现在有一个解决方案,在这个答案中有解释。

修复是在 Room 内存数据库构建器中添加一行:

db = Room
    .inMemoryDatabaseBuilder(context, AppDatabase::class.java)
    .setTransactionExecutor(Executors.newSingleThreadExecutor()) // <-- this makes all the difference
    .build()
Run Code Online (Sandbox Code Playgroud)

使用单线程执行器,测试按预期工作。