android - 房间迁移测试 MigrationTestHelper 版本
问题描述
好吧,我正在尝试测试我的数据库迁移。不幸的是,有些事情看起来不对劲。
@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 测试。
任何人都可以帮我吗?
我在这里按照谷歌指南:https ://developer.android.com/training/data-storage/room/migrating-db-versions.html
解决方案
嗯,我终于找到了。看起来我的资产文件夹中生成了错误的架构。
为了解决这个问题,这就是我所做的。
- 从 assets 文件夹中删除 1.json 和 2.json 文件(每个文件都包含数据库版本的结构)
- 回滚到版本 1 数据库(在我的代码中),构建 > 制作 projet
- 您将在资产文件夹中看到 1.json
- 进行了更改,我的意思是在我的 Table.java 文件中添加我的新列
- 构建 > 制作项目
- 您将在资产文件夹中看到 2.json
- 运行junit测试,现在工作
这是我的 java 对象和数据库版本 1 和 2 之间的区别
@Entity(tableName = "Table")
public class Table implements Parcelable {
@ColumnInfo(name = COLUMN_REFERENCE_CODE)
private String referenceCode;
}
希望这会有所帮助。
推荐阅读
- slack - 使用 Slack 斜杠命令运行本地应用程序
- html - 使用模态会导致我的“范围”重置
- angular - HostListener 慢速应用程序,检查每个像素的窗口调整大小事件
- c# - 使用原始以太网字节的 TCP 协议
- passenger - 如何在 Phusion 乘客重启时处理应用程序清理?
- mysql - 如何构建一个 SQL 来查找每个产品在不同日期和时间的 MAX?
- c# - C# - 强制窗口延迟 20 秒左右以实现蓝牙未连接
- python - Python 3.7 Scapy 安装失败
- reactjs - React “提交主机效果”在分析器中大约需要 13 秒。如何在 Chrome 开发工具中分解这些提交?
- open-source - 如何阻止对象存储服务文件链接过期?