Android 房间部分迁移测试

Android Room Partial Migration Testing

我正在处理的代码库(NewPipe) uses Android Room. It has an AppDatabase which extends RoomDatabase (the Android Room class), a StreamDAO, and a StreamEntity。我在 StreamEntity 中添加了一列,并将 @Database 版本从 3 增加到 4。我还添加了一个 Migration34.

问题是以前 a test testing the Migration from version 2 to 3. When I try to run the test, I get the error java.lang.IllegalStateException: A migration from 3 to 4 was required but not found. Please provide the necessary Migration path via RoomDatabase.Builder.addMigration(Migration ...) or allow for destructive migrations via one of the RoomDatabase.Builder.fallbackToDestructiveMigration* methods.. I can fix this error by adding .addMigrations(MIGRATION_3_4) to this line。但这也会运行从版本 34 的迁移,我想将其隔离到一个单独的测试中。

getMigratedDatabase()这个功能其实只有在测试数据验证时才需要用到(除了自动迁移验证)。我可以通过 运行 queries 在部分迁移的数据库上从(部分)迁移的数据库中获取数据,但我无法将数据作为 StreamEntity.

如何测试部分迁移数据库以及访问部分迁移数据库上的 StreamDAO

编辑: 我了解到(来自 Android 开发人员测试单一迁移)You cannot use DAO classes because they expect the latest schema.。我可以使用 (kotlin) 获取所有数据:

query("SELECT * FROM streams").run {
    DatabaseUtils.dumpCursorToString(this)
}

但是,为了便于数据测试,我无法将其转换为StreamEntity

如果你想测试只迁移了一半的数据,你必须创建一个匹配的(遗留)数据库、dao 和实体(不推荐)。

我认为您最好阅读单独的列值,然后检查这些值,或者获取这些值并自己构建 SteamEntity。

像这样 (Java):

db = helper.runMigrationsAndValidate(AppDatabase.DATABASE_NAME, 3, false, MIGRATION_2_3);
Cursor cursor = db.query("SELECT * FROM " + TEST_DB + ";" );
cursor.moveToFirst();
assertEquals(expectedColumnValue, cursor.getString(cursor.getColumnIndex("columnName1" )));
assertNull(cursor.getString(cursor.getColumnIndex("columnName2" )));

然后为整个迁移(到 v4)添加另一个测试,在那里您可以使用您的 Dao 方法并直接检查 StreamEntity 并确认 DAO 正在正确构建 StreamEntity。