我想测试我的数据库层,但我发现自己陷入了 catch-22 类型的情况。
测试用例由两部分组成:
简而言之,问题在于:
Insert是一个suspend方法,这意味着它需要运行runBlocking{}Query返回一个LiveData结果,这也是异步的。因此需要观察。有这个SO question 解释了如何做到这一点。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 …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试以下 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
测试班
@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 = …Run Code Online (Sandbox Code Playgroud)