Android Instrumented Unit Test With Room Using In Memory Database And LiveData

May 14, 2018
Use Room.inMemoryDatabaseBuilder To Avoid Overwrite Database With Test Data

NOTE: Refer to Android Instrumented Unit Test With Hamcrest if you are unfamiliar with it.

Create LiveDataTestUtil.getValue (Source) to retrive value from LiveData in Unit Test.

object LiveDataTestUtil {
    // @Throws(InterruptedException::class)
    fun <T> getValue(liveData: LiveData<T>): T {
        val data = arrayOfNulls<Any>(1)
        val latch = CountDownLatch(1)
        val observer = object : Observer<T> {
            override fun onChanged(o: T?) {
                data[0] = o
        latch.await(2, TimeUnit.SECONDS)

        return data[0] as T

Sample DatabaseTest to show

  • Room In Memory Database for Unit Testing
  • Unit Test with LiveData
  • Unit Test with Room DAO Insert
import org.hamcrest.CoreMatchers.`is` as Is

class DatabaseTest {
    // this is RoomDatabase
    private lateinit var db: AppDatabase

    fun init() {
        db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),

    fun closeDb() {

    fun testIfEmpty() {
        val liveData = db.photoPinDao().fetchAll()
        var items = LiveDataTestUtil.getValue(liveData)
        assertThat(items.size, Is(0))

    fun testInsertValue() {
        var item = PhotoPin(name="test")
        assertThat(, Is("test"))

        // could create Kotlin extension to simplified this code

        var items = getValue(db.photoPinDao().fetchAll())
        assertThat(items.size, Is(1))

        item = items[0]
        assertThat(, Is("test"))
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.