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

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.countDown()                liveData.removeObserver(this)            }        }        liveData.observeForever(observer)        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@RunWith(AndroidJUnit4::class)class DatabaseTest {    // this is RoomDatabase    private lateinit var db: AppDatabase    @Before    fun init() {        db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),                AppDatabase::class.java).build()    }    @After    fun closeDb() {        db.close()    }    @Test    fun testIfEmpty() {        val liveData = db.photoPinDao().fetchAll()        var items = LiveDataTestUtil.getValue(liveData)        assertThat(items.size, Is(0))    }    @Test    fun testInsertValue() {        var item = PhotoPin(name="test")        assertThat(item.name, Is("test"))        // could create Kotlin extension to simplified this code        db.beginTransaction()        db.photoPinDao().insert(item)        db.setTransactionSuccessful()        db.endTransaction()        var items = getValue(db.photoPinDao().fetchAll())        assertThat(items.size, Is(1))        item = items[0]        assertThat(item.name, Is("test"))    }}

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.