我正在尝试测试会议室迁移,但是测试始终失败。模型甚至都没有变化,迁移为空-测试仍然失败。我不明白自己在做什么错。
假设我们有一个实体EntityExample
,其中有两列a
和b
。主键由a
和b
组成,并且两列都有索引。代码如下:
@Entity(primaryKeys = {"a", "b"}, indices = {@Index("a"), @Index("b")})
public class EntityExample {
@NonNull public Long a;
@NonNull public Long b;
}
此外,我们的数据库版本1:
@Database(version=1,entities={EntityExample.class})
public abstract class DBExample extends RoomDatabase {
}
以及在版本2中:
@Database(version=2,entities={EntityExample.class})
public abstract class DBExample extends RoomDatabase {
}
也有迁移:
public class MigrationExample {
public final static Migration MIGRATION_1_2 = new Migration(1,2) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
}
};
}
为了访问测试中的模式,在build.gradle中添加了:
android {
sourceSets {
// Adds exported schema location as test app assets.
debug.assets.srcDirs += files("$projectDir/schemas".toString())
}
}
最后是测试:
@Config(sdk = Build.VERSION_CODES.O_MR1)
@RunWith(RobolectricTestRunner.class)
public class MigrationExampleTest {
@Rule
public MigrationTestHelper helper;
public MigrationExampleTest() {
helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(),
DBExample.class.getCanonicalName(),
new FrameworkSQLiteOpenHelperFactory());
}
@Test
public void migrationTest() throws IOException {
SupportSQLiteDatabase dbV1 = helper.createDatabase("migration-test", 1);
dbV1.close();
DBExample dbV2 = Room.databaseBuilder(
InstrumentationRegistry.getInstrumentation().getTargetContext(),
DBExample.class,
"migration-test")
.addMigrations(MigrationExample.MIGRATION_1_2)
.build();
dbV2.getOpenHelper().getWritableDatabase();
dbV2.close();
}
}
测试在带有行的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}
您可以看到(将测试输出滚动到右侧时),找到的TableInfo中缺少indices
b
的primaryKeyPosition在1和2之间有所不同。我不明白为什么,我不知道到底是什么导致测试失败,也不知道如何解决。运行该应用程序可以正常工作,不会引发任何异常。我检查了架构,除了更新的版本号(请参阅https://justpaste.it/68l2b和https://justpaste.it/3r45p)外,它们完全相同。但是,测试失败!我正在尝试测试会议室迁移,但是测试始终失败。模型甚至都没有变化,迁移为空-测试仍然失败。我不明白我在做什么错。 ...
如果您还没有,可以查看这篇关于迁移测试的好文章:https://medium.com/androiddevelopers/testing-room-migrations-be93cdb0d975