Android Room Partial Migration Testing

Viewed 188

The codebase I'm working on (NewPipe) uses Android Room. It has an AppDatabase which extends RoomDatabase (the Android Room class), a StreamDAO, and a StreamEntity. I added a column to StreamEntity, and I incremented the @Database version from 3 to 4. I also added a Migration from 3 to 4.

The problem is there was previously a test testing the Migration from version 2 to 3. When I try to run the test, I get the error java.lang.IllegalStateException: A migration from 3 to 4 was required but not found. Please provide the necessary Migration path via RoomDatabase.Builder.addMigration(Migration ...) or allow for destructive migrations via one of the RoomDatabase.Builder.fallbackToDestructiveMigration* methods.. I can fix this error by adding .addMigrations(MIGRATION_3_4) to this line. But that then also runs the migration from version 3 to 4, which I would like to isolate to a separate test.

The getMigratedDatabase() function is actually only needed in the test for data validation (in addition to the automated migration verification). I am able to get the data from the (partially) migrated database by running queries on the partially migrated database, but I can't get the data as a StreamEntity.

How can I test partially migrating the database as well as access the StreamDAO on the partially migrated database?

Edit: I understand (from the Android Developers Testing Single Migrations) that You cannot use DAO classes because they expect the latest schema.. I can get all the data out with (kotlin):

query("SELECT * FROM streams").run {
    DatabaseUtils.dumpCursorToString(this)
}

However, I can't convert it to StreamEntity for easier data testing.

1 Answers

If you want to test data which only half-migrated, you would have to create a matching (legacy) DB, dao and entities (not recommended).

I think you're better off reading the separate column values and then either just examine those, or take the values and construct the SteamEntity yourself.

Something like this (Java):

db = helper.runMigrationsAndValidate(AppDatabase.DATABASE_NAME, 3, false, MIGRATION_2_3);
Cursor cursor = db.query("SELECT * FROM " + TEST_DB + ";" );
cursor.moveToFirst();
assertEquals(expectedColumnValue, cursor.getString(cursor.getColumnIndex("columnName1" )));
assertNull(cursor.getString(cursor.getColumnIndex("columnName2" )));

Then add another test for the whole migration (to v4), there you can use your Dao methods and examine StreamEntity directly and confirm that the DAO is constructing StreamEntity properly.

Related