Cannot test ROOM Database with Flows because of the delays

28 views Asked by At

I am trying to develop a simple inventory application for myself and I am using ROOM Database with Flow as return type for the queries, so that when I update the database, the query automatically emits my list of inventory items and the UI is updated automatically.

in the DAO:

@Query("SELECT * FROM inventoryitem ORDER BY favourite = 0, count = 0")
    fun getInventory(): Flow<List<InventoryItem>>

and in the ViewModel init() block:

init {
        viewModelScope.launch(Dispatchers.IO) {
            database.inventoryDao().getInventory().collect {
                inventory.value = it
            }
        }
    }

and the inventory is displayed in the UI, so whenever I update the ROOM database, the UI is updated automatically. It works perfectly.

I am trying to write a simple insertion test for my viewModel that tests whether upon inserting a new item into the database, my inventory will actually update itself:

@Test
    fun simpleInsertTest() = runTest {
        viewModel.addInventoryItem(testItems[0])
        assertEquals(viewModel.inventory.value, listOf(testItems[0]))
    }

This test only passes if I add a sleep(200L) inbetween the two test lines, I am guessing because the ROOM insertion and the flow collection takes some time, and the test code does not wait for it with the assertion.

Is there any better way to wait for the new emission other than using this approach?

Thanks in advance

1

There are 1 answers

0
Viewed On

Add suspend to insert function in DAO and wrap addInventoryItem to try/catch block. If catch fired - test failed.