Android Room Migration 测试失败,但没有任何变化

Seb*_*ebu 6 java sqlite android database-migration android-room

我正在尝试测试 Room 迁移,但测试总是失败。甚至模型都没有变化。我只增加了版本号,迁移是空的 - 测试仍然失败。我不明白我做错了什么。

假设我们有一个 entity EntityExample,有两列ab。主键由a和组成b,我们有两列的索引。代码如下:

@Entity(primaryKeys = {"a", "b"}, indices = {@Index("a"), @Index("b")})
public class EntityExample {
    @NonNull public Long a;
    @NonNull public Long b;
}
Run Code Online (Sandbox Code Playgroud)

此外,我们在版本 1 中的数据库:

@Database(version=1,entities={EntityExample.class})
public abstract class DBExample extends RoomDatabase {
}
Run Code Online (Sandbox Code Playgroud)

在版本 2 中:

@Database(version=2,entities={EntityExample.class})
public abstract class DBExample extends RoomDatabase {
}
Run Code Online (Sandbox Code Playgroud)

此外,还有迁移:

public class MigrationExample {
    public final static Migration MIGRATION_1_2 = new Migration(1,2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {

        }
    };
}
Run Code Online (Sandbox Code Playgroud)

为了在测试中访问模式,在 build.gradle 中添加了:

android {
    sourceSets {
        // Adds exported schema location as test app assets.
        debug.assets.srcDirs += files("$projectDir/schemas".toString())
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,测试:

android {
    sourceSets {
        // Adds exported schema location as test app assets.
        debug.assets.srcDirs += files("$projectDir/schemas".toString())
    }
}
Run Code Online (Sandbox Code Playgroud)

测试失败就行dbV2.getOpenHelper().getWritableDatabase();

java.lang.IllegalStateException: Migration didn't properly handle: EntityExample(....EntityExample).
 Expected:
TableInfo{name='EntityExample', columns={a=Column{name='a', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}, b=Column{name='b', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=2, defaultValue='null'}}, foreignKeys=[], indices=[Index{name='index_EntityExample_a', unique=false, columns=[a]}, Index{name='index_EntityExample_b', unique=false, columns=[b]}]}
 Found:
TableInfo{name='EntityExample', columns={a=Column{name='a', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}, b=Column{name='b', type='INTEGER', affinity='3', notNull=true, primaryKeyPosition=1, defaultValue='null'}}, foreignKeys=[], indices=null}
Run Code Online (Sandbox Code Playgroud)

如您所见(向右滚动测试输出时),找到的 TableInfo 中缺少索引部分。此外,primaryKeyPositionb不同1和2之间,我不明白为什么,我不知道到底是什么导致测试失败了,我不知道如何解决这个问题。运行应用程序有效,不会引发异常。我检查了模式,除了更新的版本号外,它们完全相同(参见https://justpaste.it/68l2bhttps://justpaste.it/3r45p)。但是,测试失败!

djl*_*eop -1

如果您还没有,您可以查看这篇关于迁移测试的好文章:https://medium.com/androiddevelopers/testing-room-migrations-be93cdb0d975

然后,在迁移中,您必须实际迁移数据库,执行 SQL 从 1 到 2,例如通过创建索引。

Room 处理迁移链接、结构完整性和测试,但不处理迁移本身。在文档https://developer.android.com/training/data-storage/room/migration-db-versions中,他们迁移了数据库,您也应该这样做。