Testing Room and migrations

Testing Mid-level Kotlin 2.0+ API 24+ Reviewed By Best Latest Apps

Order the steps

Order a migration test from 3 to 4.

  • Insert rows using version 3 SQL
  • Run and validate the migration to version 4
  • Create the database at version 3 with MigrationTestHelper
  • Query the rows and assert they're intact with new defaults

Choose an answer, then open Show answer below to check it.

Show answer

Answer: C A B D

  1. Create the database at version 3 with MigrationTestHelper Uses the exported 3.json schema.
  2. Insert rows using version 3 SQL Data an old user would have.
  3. Run and validate the migration to version 4 Room checks the schema matches 4.json.
  4. Query the rows and assert they're intact with new defaults Proves data survives.

30-second answer

For DAOs, build an in-memory database with Room.inMemoryDatabaseBuilder, insert data, and assert on query results, including Flow emissions. These usually run as instrumented tests, or on the JVM with Robolectric or the bundled SQLite driver. For migrations, use MigrationTestHelper: create the database at the old version from the exported schema, insert rows, run the migration and check the data.

Practise saying it · 30 s. No recording, just a timer

Explain how to test Room.

Say your answer out loud, then check which of these points you covered:

  • In-memory database for DAOs
  • Assert results and flows
  • MigrationTestHelper for upgrades
  • Close after each test

Deep dive

Close the database in @After.

allowMainThreadQueries() is fine in tests.

Test every migration path users can take, not just the latest step.

Room's KMP support lets you use the bundled SQLite driver in JVM tests.

Common mistakes

  • Faking the DAO when the SQL itself is what needs testing.
  • No migration tests until a crash in production.
  • Sharing one database between tests.

Senior take & follow-ups

Mention in-memory databases for DAOs and MigrationTestHelper for upgrades.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why test SQL against a real database?

    Show hint

    Fakes can't catch wrong queries or constraints.

  2. What does MigrationTestHelper need?

    Show hint

    The exported schema JSON files.

Suggest a fix if something here is wrong or out of date.