skip to content

How do you test Room migrations with MigrationTestHelper so that a fitness app's users on versions 4, 5 and 6 all reach version 7 with their data intact?

level: seniorimportance: should knowfreq 40%

answer

  1. exported schemas in test assets
  2. create the old version, insert by SQL
  3. migrate, then validate against the target JSON
  4. check the data yourself

basics

~20 s

MigrationTestHelper creates a database at an old version from its exported schema; you insert rows by SQL, then runMigrationsAndValidate(7, migrations) runs Room's path and checks the schema against version 7's JSON. Assert the data yourself, per start version.

solid answer

~40 s

Add the Room testing artifact, make the exported schema JSON available to the test as assets (the Room Gradle plugin does this for instrumented tests since 2.7.0), and declare `MigrationTestHelper` as a JUnit rule built with the database class. For each starting version, call `createDatabase(4)`, insert rows with SQL (DAOs expect the latest schema), close it, then call `runMigrationsAndValidate(7, listOf(...))`. The helper picks migrations with Room's own algorithm, adds the database's auto-migrations, and throws `IllegalStateException` if the resulting schema differs from `7.json`. It does not check rows, so query the migrated connection and assert the values. Repeat from 5 and 6, and add one test that opens the real database with every migration registered.

code

kotlin · 27 lines
kotlin
@RunWith(AndroidJUnit4::class)
class FitnessMigrationTest {
    private val instrumentation = InstrumentationRegistry.getInstrumentation()

    @get:Rule
    val helper = MigrationTestHelper(
        instrumentation = instrumentation,
        file = instrumentation.targetContext.getDatabasePath("migration-test"),
        driver = AndroidSQLiteDriver(),
        databaseClass = FitnessDatabase::class,
    )

    @Test
    fun from4To7KeepsWorkouts() = runTest {
        val old = helper.createDatabase(4)
        old.execSQL("INSERT INTO workouts (id, started_at, duration) VALUES (1, 1700000000000, 1800)")
        old.close()

        // MIGRATION_4_5 is manual; 5 to 6 and 6 to 7 are auto-migrations the helper adds itself.
        val migrated = helper.runMigrationsAndValidate(7, listOf(MIGRATION_4_5))
        migrated.prepare("SELECT duration_seconds FROM workouts WHERE id = 1").use { stmt ->
            assertTrue(stmt.step())
            assertEquals(1800L, stmt.getLong(0))
        }
        migrated.close()
    }
}

go deeper

for a junior

Know that Room ships MigrationTestHelper, that it needs exported schemas, and that you create an old version, migrate it and check it.

for a middle

Walk through createDatabase, raw SQL inserts, runMigrationsAndValidate and the data assertions, and why DAOs cannot be used on the old file.

for a senior

Test from every shipped start version, include provided specs, add a full-builder test that catches unregistered migrations, and assert data, not just shape.

for a principal

Make per-version migration tests a release gate in CI and decide how many old versions the team commits to keep testing.

## What the helper is for A migration bug only shows on devices holding an older database file, so a clean-install test never exercises it. Room's **`MigrationTestHelper`**, in the `room-testing` artifact (`room3-testing` in Room 3.0), recreates those older files in a test. It reads your **exported schema JSON** for a given version, creates a database with exactly that shape, and then runs and validates migrations on it. It is a JUnit 4 rule (it extends `TestWatcher`) and closes the databases it opened when the test ends. ## Setup - **Exported schemas.** `exportSchema` must be on and a schema directory configured, because the helper opens `<version>.json`. - **Schemas reachable from the test.** With the Room Gradle plugin, since 2.7.0 the exported schemas are added to the instrumented test's sources automatically so the helper can read them. Without the plugin, add the schema directory as an `androidTest` assets source. A missing file fails with `FileNotFoundException` ("Cannot find the schema file in the assets folder"). - **Construct it with the database class.** Passing the class lets the helper discover the database's `@AutoMigration`s and include them, the support Room 2.4.0 added. Room 3.0's constructor also takes a `SQLiteDriver` and the database `File`; specs marked `@ProvidedAutoMigrationSpec` go in `autoMigrationSpecs`. ## One test per starting version 1. **`createDatabase(4)`** creates the file at version 4 from `4.json` and returns a connection (Room 2.x's classic form, `createDatabase(name, 4)`, returns a `SupportSQLiteDatabase`). 2. **Insert representative rows with raw SQL.** The DAOs are compiled for version 7 and cannot be used on a version-4 file. 3. **Close** that connection. 4. **`runMigrationsAndValidate(7, migrations)`** reopens the file, finds a path with the same algorithm Room uses at runtime, runs it, and validates every table against `7.json`. Auto-migrations are already included; a manual migration in the list takes precedence over an auto-migration for the same versions. 5. **Query the returned connection** and assert the data: values moved, defaults filled, nothing lost. For the fitness app, run this from 4, from 5 and from 6, because each start version may take a different path, for instance a shortcut from 4 that versions 5 and 6 never use. A parameterised test over the list of start versions keeps this to one test body. ## What validation checks and what it does not | Checked by the helper | Your job | |---|---| | Tables, columns, affinity, NOT NULL, primary keys, foreign keys, indices | Rows survived and were transformed correctly | | A path exists from the start version | Every shipped start version has a test | | The result matches the target version's JSON | The JSON matches what you meant to ship | ## Room 2.x and Room 3.0 forms | Step | Room 2.x classic helper | Room 3.0 helper | |---|---|---| | Construct | `MigrationTestHelper(instrumentation, FitnessDatabase::class.java)` | `MigrationTestHelper(instrumentation, file, driver, FitnessDatabase::class)` | | Create | `createDatabase(name, version)` returns a `SupportSQLiteDatabase` | suspend `createDatabase(version)` returns a `SQLiteConnection` | | Migrate | `runMigrationsAndValidate(name, version, validateDroppedTables, vararg migrations)` | suspend `runMigrationsAndValidate(version, migrations)` | The 2.x `validateDroppedTables` flag makes an extra table left in the database fail validation; when false, extra tables are ignored, which is what the runtime does. ## Testing the full chain The Room documentation recommends one more test: create the oldest version with the helper, close it, then build the real database with `Room.databaseBuilder(...)` and every migration registered, and open it. When the test calls the same builder code the app uses, a migration you forgot to pass to `addMigrations()` fails here, and Room validates against the entities compiled into the app. ## Pitfalls - **Rows that do not exercise the change.** Validation passes on empty tables; insert data that the migration must move or convert, including nulls and edge values. - **A stale or missing JSON file.** The helper validates against the exported file, so commit the schema of every released version. - **Testing only the newest step.** Users skip releases, so the start versions to test are the ones still installed, not just the previous one. - **Forgetting provided specs.** A spec marked `@ProvidedAutoMigrationSpec` must be passed to the helper, or the auto-migration that needs it cannot be built. - **Treating a green run as data safety.** The helper proves the shape; only your queries prove the content.

  • All migration tests pass, yet production users on version 5 crash with 'A migration from 5 to 7 was required but not found'. How?
    The tests passed the migration list straight to the helper, so they never exercised the app's builder. If `MIGRATION_5_6` was written but not passed to `addMigrations()` in production code, only a test that builds the real database with the production migration list, after creating version 5 with the helper, would catch it.
  • Your app's @AutoMigration uses a spec annotated @ProvidedAutoMigrationSpec. What does the test need?
    The helper cannot construct a provided spec itself, so you pass an instance through the constructor's `autoMigrationSpecs` list, just as the production builder receives it through `addAutoMigrationSpec()`. Without it, the helper cannot build the auto-migration that needs it.

  • runMigrationsAndValidate also verifies that the rows survived
  • You can insert test data through the DAOs after createDatabase(4)
  • Testing only the previous version to the new one is enough
  • The helper works without exported schema files
  • Auto-migrations must be listed by hand in runMigrationsAndValidate

Code assumes Room 3.0's androidx.room3.testing.MigrationTestHelper (driver and file in the constructor, suspend functions); Room 2.x's classic helper takes a database name and returns a SupportSQLiteDatabase.