Search code examples
androidrx-java2android-room

Tests fail when testing Room insertion with Rx


I'm trying to make a simple CRUD test on my single Entity but I can't figure out what I have done wrong, thus test is always failing with AssertionError.

This is my database setup:

@Database(entities = [Habit::class], version = 1)
@TypeConverters(Converter::class)
abstract class CareFlectDatabase : RoomDatabase() {
    abstract fun habitDao(): HabitDao
}

Entity:

@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?
)

And now the tests:

@Test
fun insertHabitTest() {
    //dependencies correctly instatiated
    //this line does complete
    habitDao.insertHabit(habit)

    habitDao.selectAll().test().assertValue { list ->
        //this line fails
        list.isNotEmpty()
    }
}

My dao queries:

@Query("SELECT * FROM user_habits")
fun selectAll(): Flowable<List<Habit>>

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertHabit(habit: Habit): Completable

If I'm missing something from the dependencies, please give it a look:

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'

Solution

  • SOLVED: The only thing I was missing was the blockingAwait() call when my INSERT query happens and test passes.

    So instead of:

    habitDao.insertHabit(habit)
    

    Should be:

    habitDao.insertHabit(habit).blockingAwait()
    

    More reference here.