How do you test that a Room DAO's Flow query re-emits after an insert, using an in-memory database and runTest?
answer
- a database that vanishes on close
- the Flow never completes
- the first emission is the current state
- wait for a condition, not a count
basics
~10 sBuild the database with Room.inMemoryDatabaseBuilder, insert inside runTest, then await the Flow with first { condition } rather than toList(), because Room's Flow never completes and re-emits asynchronously on Room's own dispatcher.
solid answer
~40 sCreate the database with `Room.inMemoryDatabaseBuilder`, so each test starts empty and nothing survives `close()` in `@After`; with Room 3.0 the testing guide adds `setDriver(BundledSQLiteDriver())`. Inside `runTest`, call the suspend insert, then read the stream with `dao.observeInbox().first { it.size == 1 }`. Three Room facts shape the test. The observable `Flow` never completes, so `toList()` hangs until the test times out. The first emission is the current state, so a collector started after the insert already sees the row and may never get a second emission. And the re-run happens on Room's query context (`Dispatchers.IO` by default), not on the test dispatcher, so virtual time does not drive it; waiting on a condition does. Cancel any collector before closing the database: since Room 3.0.2, queries after `close()` throw `IllegalStateException`.
code
kotlin · 25 lines@RunWith(AndroidJUnit4::class)
class InboxDaoTest {
private lateinit var db: InboxDatabase
private lateinit var dao: InboxDao
@Before
fun createDb() {
val context = ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder<InboxDatabase>(context)
.setDriver(BundledSQLiteDriver())
.build()
dao = db.inboxDao()
}
@After
fun closeDb() = db.close()
@Test
fun inboxReEmitsAfterInsert() = runTest {
dao.insert(Message(id = 7L, folder = "inbox", subject = "Hi"))
// Room's Flow never completes: wait for a matching emission instead of toList().
val rows = dao.observeInbox().first { list -> list.any { it.id == 7L } }
assertEquals(1, rows.size)
}
}go deeper
Recall that DAO tests use Room.inMemoryDatabaseBuilder for a fresh, throwaway database per test, created before and closed after each test.
Explain why toList() hangs on a Room Flow, why the first emission already reflects earlier inserts, and why first with a predicate is the robust assertion.
Show you can keep such tests reliable: no dependence on emission counts, collectors in backgroundScope, no reliance on virtual time for Room's dispatcher, and closing only after collectors stop.
Decide where a team runs its database tests, on devices or as host JVM tests with the bundled driver, weighing speed in CI against fidelity to the production SQLite.
## What the test proves The behaviour under test is the core of an offline-first inbox: when a sync job inserts a message, the inbox query's `Flow` emits a list that contains it. Mocking the DAO cannot prove that, because the re-emission is produced by Room's invalidation tracker and generated code. The test needs a **real Room database**, which for speed and isolation is an **in-memory** one. ## Setting up the database `Room.inMemoryDatabaseBuilder` builds a database that lives only in memory: it starts empty, and its data is gone when the instance is closed. That makes each test hermetic. - Create it in `@Before` and close it in `@After`, one instance per test. - Room 3.0's testing guide configures `setDriver(BundledSQLiteDriver())`, which ships its own SQLite build, so the same SQLite runs on a device, an emulator and a JVM host test. - On a device or emulator the builder takes the application `Context`; Room 3.0 also has an overload without a `Context` for host JVM tests. - The testing guide recommends device tests, or host JVM tests through Room's multiplatform support, over Robolectric for database code. ## Three Room facts that shape the assertions | Fact | Consequence in the test | |---|---| | An observable query's `Flow` never completes; it waits for the next write | `toList()` or `collect` without a limit never returns, and `runTest` eventually fails on its timeout | | Collection starts with an emission of the current rows | a collector that starts after the insert already sees the row, so waiting for a "second" emission can hang | | Re-runs happen on Room's query context, `Dispatchers.IO` by default | the test scheduler's virtual time does not run Room's work; the test must wait for a result | From those facts follow the patterns that work: 1. **Await a condition.** After the insert, `dao.observeInbox().first { rows -> rows.any { it.id == 7L } }` returns as soon as an emission satisfies the predicate, whether that is the first emission or a later one. It is race-free because it does not depend on when collection started. 2. **Collect in the background when the sequence matters.** Start a collector in `backgroundScope` that records emissions into a list, wait until the initial (empty) emission has arrived, insert, then wait until the list grows. `backgroundScope` is cancelled when the test body finishes, so the endless `Flow` does not keep `runTest` waiting. 3. **Bound the stream.** `take(n)` is only safe when you know exactly which emissions will occur; conflation in Room's `Flow` can merge rapid writes into one emission, so counting emissions is fragile. ## Closing the database safely Close the database only after every collector is gone. Since Room 3.0.2, suspending queries and invalidation tracker operations throw `IllegalStateException` once the database is closed, so a collector still running when `@After` calls `close()` turns into a failure. A collector in `backgroundScope` is cancelled when the test body finishes, before `@After` runs; one launched directly in the test's own scope would instead keep `runTest` waiting for it. ## What not to copy from the coroutine-testing playbook General coroutine testing advice says to inject the test dispatcher everywhere so virtual time controls the code. With Room the default leaves the query work on `Dispatchers.IO`, outside the scheduler, and that is fine: the test waits on a condition instead of advancing time. The details of `runTest`, `StandardTestDispatcher` and virtual time belong with the Kotlin coroutine-testing material; the Room-specific knowledge is the endless `Flow`, the initial emission and where the re-run executes. ## Mistakes reviewers catch - Calling `toList()` on a Room `Flow` and watching the test time out. - Using `take(2)` after the insert, so the first emission already holds the row and the second may never come. - Relying on `advanceUntilIdle()` to deliver Room's re-emission, which runs on another dispatcher. - Sharing one database across tests, so rows from one test leak into the next. - Leaving a collector in a scope that outlives the test, then closing the database under it. A good answer sets up the in-memory database, explains why `first { }` beats counting emissions, and names where Room's work actually runs.
- How would you assert both the empty initial emission and the emission after the insert?Launch a collector in `backgroundScope` that appends each emission to a list, wait until the list holds the initial empty result, insert, then wait until a later element contains the row. `backgroundScope` is cancelled when the test body ends, so the endless Room `Flow` does not block `runTest`. Assert on the first and last elements rather than on an exact count, because Room's `Flow` is conflated.
- Why does advanceUntilIdle() not deliver the re-emission in a Room test?`advanceUntilIdle()` only runs work scheduled on the test scheduler. Room runs its query and the re-run after a write on its own query context, `Dispatchers.IO` by default, which the scheduler does not control. The emission arrives on real threads, so the test suspends until it does, for example with `first { }`.
- Collect the Room Flow with toList() and assert on the result.
- advanceUntilIdle() forces Room to deliver the next emission.
- The first emission only arrives after the first write to the table.
- One shared in-memory database for the whole test class is fine.
- Mock the DAO to prove that the Flow re-emits after an insert.
Assumes Room 3.0.3 (androidx.room3) with the testing guide's BundledSQLiteDriver; since 3.0.2, suspending queries and invalidation tracker operations throw IllegalStateException after the database is closed.