You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

测试Room AutoMigrations时runMigrationsAndValidate需传入什么参数?

解决方案

当你使用Room自动迁移时,编译期会根据你在@Database注解中声明的autoMigrations规则,自动生成对应版本的Migration实现类,你直接实例化这个生成类传入即可。


具体步骤

  1. 首先确认你的数据库类已经正确配置自动迁移和Schema导出:
@Database(
    entities = [XXXEntity::class],
    version = 2,
    // 声明1到2版本的自动迁移
    autoMigrations = [AutoMigration(from = 1, to = 2)],
    // 必须开启Schema导出,否则自动迁移无法生成
    exportSchema = true
)
abstract class MigrationDb : RoomDatabase() {
    // 数据库DAO定义等逻辑
}
  1. 编译项目后,Room会生成命名规则为[你的数据库类名]_AutoMigration_[起始版本]_[目标版本]的迁移类,对应你1升2的场景,如果数据库类叫MigrationDb,生成的类就是MigrationDb_AutoMigration_1_2
  2. 把这个类的实例传入runMigrationsAndValidate的参数位即可,修改后的测试代码如下:
@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 {
            // 版本1的数据库,可执行SQL插入测试数据
            execSQL(...)

            // 关闭准备迁移
            close()
        }

        // 直接传入自动生成的迁移类实例即可
        db = helper.runMigrationsAndValidate(TEST_DB, 2, true, MigrationDb_AutoMigration_1_2())
    }
}

常见注意点

  • 如果使用Kotlin开发,要确保已经开启了kapt或者KSP注解处理器,否则自动生成的类不会正常产出
  • 要是有多个版本的自动迁移需要串联测试,按顺序把所有对应版本的自动迁移实例都传入参数即可

内容的提问来源于stack exchange,提问作者Florian Walther

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 03:48:04