8

When using Room AutoMigrations, the Migration itself is automatically generated. But in order to unit test the migration, I have to pass a Migration object to runMigrationsAndValidate. What should I pass here?

@RunWith(AndroidJUnit4::class)
class MigrationTest {
    private val TEST_DB = "migration-test"

    @Rule
    val helper: MigrationTestHelper = MigrationTestHelper(
            InstrumentationRegistry.getInstrumentation(),
            MigrationDb::class.java.canonicalName,
            FrameworkSQLiteOpenHelperFactory()
    )

    @Test
    @Throws(IOException::class)
    fun migrate1To2() {
        var db = helper.createDatabase(TEST_DB, 1).apply {
            // db has schema version 1. insert some data using SQL queries.
            execSQL(...)

            // Prepare for the next version.
            close()
        }

        // Re-open the database with version 2 and provide
        // Migration as the migration process.
        db = helper.runMigrationsAndValidate(TEST_DB, 2, true, /* WHAT TO PASS HERE? */)
    }
}
Florian Walther
  • 6,237
  • 5
  • 46
  • 104

1 Answers1

6

As far as i understand, in the new AutoMigration, we are not required to handle migrations ourself.

So at first, update your MigrationTestHelper to a API which supports AutoMigration:

import androidx.room.testing.MigrationTestHelper
import androidx.test.platform.app.InstrumentationRegistry

val helper = MigrationTestHelper(
    InstrumentationRegistry.getInstrumentation(),
    YourDatabase::class.java
)

And then just remove the Migration from the call:

db = helper.runMigrationsAndValidate(TEST_DB, 2, true)

tzanke
  • 198
  • 1
  • 12
  • 2
    We can now just remove the empty ArrayList and just use the constructor like so: ```MigrationTestHelper(InstrumentationRegistry.getInstrumentation(), Database::class.java)``` – Ishaan Garg Aug 27 '22 at 19:31