Android 房间迁移测试迁移TestHelper版本
嗯,我正在尝试测试我的数据库迁移。不幸的是,有些事情看起来不对劲Android 房间迁移测试迁移TestHelper版本,android,android-room,database-migration,android-testing,Android,Android Room,Database Migration,Android Testing,嗯,我正在尝试测试我的数据库迁移。不幸的是,有些事情看起来不对劲 @RunWith(AndroidJUnit4ClassRunner.class) public class MigrationTest { private static final String TEST_DB = "migration-test"; @Rule public MigrationTestHelper helper; public MigrationTest() {
@RunWith(AndroidJUnit4ClassRunner.class)
public class MigrationTest {
private static final String TEST_DB = "migration-test";
@Rule
public MigrationTestHelper helper;
public MigrationTest() {
helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(),
AppDatabase.class.getCanonicalName(),
new FrameworkSQLiteOpenHelperFactory());
}
@Test
public void migrateAll() throws IOException {
// Create earliest version of the database.
SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 1);
db.close();
// Open latest version of the database. Room will validate the schema
// once all migrations execute.
AppDatabase appDb = Room.databaseBuilder(
InstrumentationRegistry.getInstrumentation().getTargetContext(),
AppDatabase.class,
TEST_DB)
.addMigrations(ALL_MIGRATIONS).build();
appDb.getOpenHelper().getWritableDatabase();
appDb.close();
}
// Array of all migrations
private static final Migration[] ALL_MIGRATIONS = new Migration[]{MIGRATION_1_2};
}
迁移代码
public static final Migration MIGRATION_1_2 = new Migration(1, 2) {
@Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE mytable ADD COLUMN reference_code TEXT");
}
};
在真正的迁移中,一切都很好,但在junit测试用例中,我有以下错误
E/SQLiteLog: (1) duplicate column name: reference_code
E/TestRunner: failed: migrateAll(com.apps.MigrationTest)
E/TestRunner: ----- begin exception -----
E/TestRunner: android.database.sqlite.SQLiteException: duplicate column name: reference_code (code 1 SQLITE_ERROR): , while compiling: ALTER TABLE mytable ADD COLUMN reference_code TEXT
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:986)
at a
据我所知,它看起来像SupportSQLiteDatabase db=helper.createDatabase(TEST_db,1)代码>正在创建数据库的架构V2(而不是版本1)。
因此,新列被标记为重复
要修复它,我必须将version=1
回滚到@Database
类,然后再次启动junit测试
有人能帮我吗
我在这里遵循谷歌指南:嗯,我终于找到了它。“我的资产”文件夹中似乎生成了错误的架构
为了解决这个问题,以下是我所做的
从资产文件夹中删除1.json和2.json文件(每个文件都包含数据库版本的结构)
回滚到版本1数据库(在我的代码中),build>makeprojet
您将在资产文件夹中看到1.json
进行了更改,我的意思是在Table.java文件中添加新列
构建>生成projet
您将在资产文件夹中看到2.json
运行junit测试,现在开始工作
这里是我的java对象和数据库版本1和版本2的区别
@Entity(tableName = "Table")
public class Table implements Parcelable {
@ColumnInfo(name = COLUMN_REFERENCE_CODE)
private String referenceCode;
}
希望这会有所帮助