Skip to content

Unit tests on RoomDB

Devrath edited this page Jul 6, 2021 · 4 revisions

Initial set-up for the local database

  • It is important that we write the unit tests for the local DB as instrumentation tests since we need to test the DB works on a device.
  • Important point to note here is that the DB that we use must not be global initialized, meaning its initialization must be done in a setup function. Otherwise, this will lead to flaky tests.
  • We use in-memory database builder because we don't want to store the states in the RAM instead of storage, This is ideal for writing tests.

Declaring the room-db

private lateinit var database : ShoppingItemDatabase = Room.inMemoryDatabaseBuilder(
     ApplicationProvider.getApplicationContext(),
     ShoppingItemDatabase::class.java
).allowMainThreadQueries().build()
  • ApplicationProvider.getApplicationContext() -> Context of the application
  • .allowMainThreadQueries() -> This allows us to execute the queries in main thread. By default, the room database queries run in the background thread. But due to this feature, causes issues in writing test cases since asynchronous threads are hard to control and may result in flaky tests, due to this we explicitly want the thread to run in the main thread.

Using runBlockingTest to execute a test

  • This is required to execute the coroutines in the main thread
  • We can use runBlocking but runBlockingTest is an optimized way for the test cases. The importance here is that whenever there is a delay explicitly in co-routines this runBlockingTest will skip it so that the tests execute faster.

Backbone of test

@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
@SmallTest
class ShoppingDaoTest {

    @get:Rule
    var instantTaskExecutorRule = InstantTaskExecutorRule()

    private lateinit var database: ShoppingItemDatabase
    private lateinit var dao: ShoppingDao

    @Before
    fun setup() {
        database = Room.inMemoryDatabaseBuilder(
            ApplicationProvider.getApplicationContext(),
            ShoppingItemDatabase::class.java
        ).allowMainThreadQueries().build()
        dao = database.shoppingDao()
    }

    @After
    fun teardown() {
        database.close()
    }

    @Test
    fun insertShoppingItem() = runBlockingTest {
       // Our Test 
    }

}
Clone this wiki locally