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")) }}