我想测试我的数据库层,但我陷入了第 22 条军规类型的情况。
测试用例由两部分组成:
简而言之,问题在于:
-
Insert
is a suspend
方法,这意味着它需要运行在runBlocking{}
-
Query
返回一个LiveData
结果,这也是异步的。因此需要观察。有this https://stackoverflow.com/questions/44270688/unit-testing-room-and-livedataSO问题解释了如何做到这一点。
- 但是,为了根据上面的链接观察 LiveData,我必须使用
InstantTaskExecutorRule
。 (否则我得到java.lang.IllegalStateException: Cannot invoke observeForever on a background thread.
)
-
这适用于大多数情况,但不适用于
@Transaction
- 带注释的 DAO 方法。测试永远不会结束。我认为等待某些事务线程时陷入僵局。
- 删除
InstantTaskExecutorRule
让 Transaction-Insert 方法完成,但随后我无法断言其结果,因为我需要规则才能观察数据。
详细说明
My 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)
}
}
测试用例是:
@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
}
}
The 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
}
测试这个场景的正确方法是什么?我在开发数据库映射层时需要这些类型的测试,以确保一切按我的预期工作。