-
Notifications
You must be signed in to change notification settings - Fork 0
Unit tests on RoomDB
Devrath edited this page Jul 6, 2021
·
4 revisions
- 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.
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.
- This is required to execute the coroutines in the main thread
- We can use
runBlocking
butrunBlockingTest
is an optimized way for the test cases. The importance here is that whenever there is adelay
explicitly in co-routines thisrunBlockingTest
will skip it so that the tests execute faster.
@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
}
}