vendredi 22 février 2019

Log and Unit testing in Kotlin Android

I am fairly new to android-x and using Room for the first time. This seems like it should be dead simple. yet I am having some issues with my setup and test.

I have a Unit Test that is failing

Error: java.lang.AssertionError:

Expected :1

Actual :null

I hope someone is able to assist. not sure what else to add (SO requires me to add more content to post this lol). So hopefully someone can see where I am going wrong.

class LogTest {
    //setup db
    private lateinit var logDao: LogDao
    private lateinit var testAppDatabase: AppDatabase

    @Before
    fun setUp() {
        val context = ApplicationProvider.getApplicationContext<Context>()
        testAppDatabase = Room.inMemoryDatabaseBuilder(context, AppDatabase::class.java).allowMainThreadQueries().build()
        logDao = testAppDatabase.getLogDao()
    }

    @After
    @Throws(IOException::class)
    fun closeDb() {
        testAppDatabase.close()
    }

    @Test
    @Throws(Exception::class)
    fun `log Database is Empty on Start`() {
        assertEquals(null, logDao.getAllLogs().value?.size)

        val testLog = LogModel("Test", "Test", 0, 0, 0.0, 0.0)
        logDao.insertAll(testLog)
        assertEquals(1, logDao.getAllLogs().value?.size)
    }
}

@Entity(tableName = "Logs")
data class LogModel (
    @ColumnInfo(name = "tag") var tag: String,
    @ColumnInfo(name = "msg") var msg: String,
    @ColumnInfo(name = "device_id") var deviceID: Int,
    @ColumnInfo(name = "user_id") var userID: Int,
    @ColumnInfo(name = "latitude") var latitude: Double,
    @ColumnInfo(name = "longitude") var longitude: Double
) {
    @PrimaryKey(autoGenerate = true) var id: Long? = null
    //@ColumnInfo(name = "timestamp") var timestamp: String? = null
}


@Dao
interface LogDao {
    @Query("SELECT * FROM Logs")
    fun getAllLogs(): LiveData<List<LogModel>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(vararg logs: LogModel)
}


@Database(entities = [LogModel::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    //Database to be initialised here
    abstract fun getLogDao(): LogDao

    companion object {
        @Volatile
        private var INSTANCE: AppDatabase? = null

        fun getDatabase(context: Context): AppDatabase {
            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }
            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    AppDatabase::class.java,
                    "My_Database"
                ).build()
                INSTANCE = instance
                return instance
            }
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire