I am trying to test an in-memory Room db which has...
# android
s
I am trying to test an in-memory Room db which has suspend functions but the dao functions don't seem to be running in runBlocking. And tests fail.
Copy code
@RunWith(AndroidJUnit4::class)
class SomeDaoTest {

  private lateinit var database: AppDatabase
  private lateinit var someDao: SomeDao

  @get:Rule
  var instantTaskExecutorRule = InstantTaskExecutorRule()

  @Before
  fun createDb() = runBlocking {
    val context = InstrumentationRegistry.getInstrumentation().targetContext
    database = Room
      .inMemoryDatabaseBuilder(context, AppDatabase::class.java)
      // needed to run @Transaction block
      .setTransactionExecutor(Executors.newSingleThreadExecutor())
      .build()
    someDao = database.someDao()

    someDao.insertAll(dummy1, dummy2)
  }

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

  @Test
  fun testDeleteAll() = runBlocking {
      val someData = someDao.getData().getOrAwaitValue()
      someDao.deleteAll()
      assertEquals(0, someData.size)
    }
Any help on how I should do it or how to troubleshoot it would be nice.
c
I guess
getOrAwaitValue
is a suspend function and is „waiting“ for data to be reported. If you call the
deleteAll
before the await it should work.
s
It comes from LiveDataTestUtil.kt from Google's Unit-testing LiveData and other common observability problems. I think I misunderstood it. It gets or waits for a value from LiveData but it doesn't observer it continuously. I was calling it before so it showed before data.
c
Ah, okay. But if it is LiveData, why are you using
runBlocking
from Coroutines?
s
Some operations are suspend functions. I am using LiveData as a return type for my db queries. Will eventually switch to Flow.