在单元测试文件中插入值时未找到列(房间迁移)

时间:2020-07-15 16:29:36

标签: android testing android-instrumentation

我正在尝试测试Room数据库的迁移,但这确实发生了

[android.database.sqlite.SQLiteException: no such column: title (Sqlite code 1): , while compiling: INSERT INTO post(userId,id,title,body) VALUES (1000,1,title,body);, (OS error - 2:No such file or directory)]

但是数据库中已经有一列(这是从中生成数据库的json文件)

{
  "formatVersion": 1,
  "database": {
    "version": 2,
    "identityHash": "2b41ccd83f42b66424a73d1acae4ee63",
    "entities": [
      {
        "tableName": "post",
        "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `userId` INTEGER NOT NULL, `title` TEXT NOT NULL, `body` TEXT NOT NULL, PRIMARY KEY(`id`))",
        "fields": [
          {
            "fieldPath": "id",
            "columnName": "id",
            "affinity": "INTEGER",
            "notNull": true
          },
          {
            "fieldPath": "userId",
            "columnName": "userId",
            "affinity": "INTEGER",
            "notNull": true
          },
          {
            "fieldPath": "title",
            "columnName": "title",
            "affinity": "TEXT",
            "notNull": true
          },
          {
            "fieldPath": "body",
            "columnName": "body",
            "affinity": "TEXT",
            "notNull": true
          }
        ],
        "primaryKey": {
          "columnNames": [
            "id"
          ],
          "autoGenerate": false
        },
        "indices": [],
        "foreignKeys": []
      }
    ],
    "views": [],
    "setupQueries": [
      "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
      "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '2b41ccd83f42b66424a73d1acae4ee63')"
    ]
  }
}

这是迁移代码

 @RunWith(AndroidJUnit4::class)
class Migration1Test {
    private val TEST_DB = "migration-test"
    private lateinit var db: AppDatabase
    private lateinit var postDAO: PostDAO
    var postTest = Post(1, 1000, "title", "body")

    private val ALL_MIGRATIONS = arrayOf(
        AppDatabase.MIGRATION_1_2,AppDatabase.MIGRATION_2_3
    )
    @Before
    fun createDb() {
        val context = InstrumentationRegistry.getInstrumentation().targetContext
        db = Room.inMemoryDatabaseBuilder(
            context, AppDatabase::class.java).build()
        postDAO = db.postDao()
    }
    //@Rule
    @get:Rule
    public val helper: MigrationTestHelper = MigrationTestHelper(
        InstrumentationRegistry.getInstrumentation(),
        AppDatabase::class.java.canonicalName,
        FrameworkSQLiteOpenHelperFactory()
    )

    @Test
    @Throws(IOException::class)
    fun migrateDBfrom2to3() {
        // Create earliest version of the database.
        helper.createDatabase(TEST_DB, 2).apply {
//            execSQL(
//                "CREATE TABLE `Post` (`userId` INTEGER,`id` INTEGER,`body` TEXT,`title` TEXT, " +
//                        "PRIMARY KEY(`userId`))"
//            )
            execSQL(
                                       "INSERT INTO post(userId,id,title,body)" +
                       " VALUES (${postTest.userId},${postTest.id},${postTest.title},${postTest.body});  "
            )
            close()
        }

        // Open latest version of the database. Room will validate the schema
        // once all migrations execute.
        db = Room.databaseBuilder(
            InstrumentationRegistry.getInstrumentation().targetContext,
            AppDatabase::class.java,
            TEST_DB
        ).addMigrations(AppDatabase.MIGRATION_2_3)
           .createFromAsset("databases/RxDb.db")
            .build().apply {
                openHelper.writableDatabase
                close()
            }
        val post=postDAO.findPostWithId(postTest.id)
        Assert.assertEquals(post.id, postTest.id);
        Assert.assertEquals(post.body, postTest.body);
        Assert.assertEquals(post.check, null);

    }

}

迁移方法:

 val MIGRATION_2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL(
                    "ALTER TABLE `post` ADD `check` TEXT "
                )

            }
        }

我什至用Android Debug Database进行了检查,结果如下(“ title”列存在):enter image description here

有人可以给我一个建议吗?我整天搞砸了

0 个答案:

没有答案