我正在尝试对单个实体进行简单的CRUD测试,但是我无法弄清楚自己做错了什么,因此测试总是失败,并显示AssertionError
。
这是我的数据库设置:
@Database(entities = [Habit::class], version = 1)
@TypeConverters(Converter::class)
abstract class CareFlectDatabase : RoomDatabase() {
abstract fun habitDao(): HabitDao
}
实体:
@Entity(tableName = "user_habits")
data class Habit(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
val id: Long?,
@ColumnInfo(name = "habit_title")
val habitTitle: String?,
@ColumnInfo(name = "start_date")
val startDate: Date?,
@ColumnInfo(name = "end_date")
val endDate: Date?,
@ColumnInfo(name = "receive_notification")
val receiveNotification: Boolean?
)
现在是测试:
@Test
fun insertHabitTest() {
//dependencies correctly instatiated
//this line does complete
habitDao.insertHabit(habit)
habitDao.selectAll().test().assertValue { list ->
//this line fails
list.isNotEmpty()
}
}
我的道查询:
@Query("SELECT * FROM user_habits")
fun selectAll(): Flowable<List<Habit>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertHabit(habit: Habit): Completable
如果我在依赖项中缺少某些内容,请看一下:
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
implementation "androidx.room:room-rxjava2:$room_version"
testImplementation "androidx.room:room-testing:$room_version"
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.9'
//tests
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test:core:1.2.0'
testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-core:2.28.2'
尝试类似的东西
@Before
fun before() {
RxAndroidPlugins.reset()
RxJavaPlugins.reset()
RxJavaPlugins.setIoSchedulerHandler { Schedulers.trampoline() }
RxAndroidPlugins.setInitMainThreadSchedulerHandler {
Schedulers.trampoline()
}
}
@Test
fun insertHabitTest() {
//dependencies correctly instatiated
//this line does complete
habitDao.insertHabit(habit).subscribeOn(Schedulers.io()).subscribe()
val observer = habitDao.selectAll().subscribeOn(Schedulers.io()).test()
observer.awaitTerminalEvent()
observer.assertNoErrors().assertValue { list ->
//this line fails
list.isNotEmpty()
}}
已解决:当我的blockingAwait()
查询发生并通过测试时,我唯一缺少的是INSERT
调用。
所以代替:
habitDao.insertHabit(habit)
应该是:
habitDao.insertHabit(habit).blockingAwait()
更多参考here。