[英]How to do Room migration testing properly by inserting and testing data?
I'm trying to test Room DB after including a new Column date
.我正在尝试在包含新的 Column
date
后测试 Room DB。 But I'm not getting how to insert data as I cannot use context in Testing.java file.但是我不知道如何插入数据,因为我无法在 Testing.java 文件中使用上下文。
my code looks like this,我的代码看起来像这样,
@RunWith(AndroidJUnit4.class)
public class MigrationTest {
private static final String TEST_DB = "note_database";
@Rule
public MigrationTestHelper helper;
public MigrationTest() {
helper = new MigrationTestHelper(InstrumentationRegistry.getInstrumentation(),
NoteDatabase.class.getCanonicalName(),
new FrameworkSQLiteOpenHelperFactory());
}
@Test
public void migrateAll() throws IOException {
// Create earliest version of the database.
SupportSQLiteDatabase db = helper.createDatabase(TEST_DB, 2);
db.execSQL("INSERT INTO note_table (title,description,priority,date)" +
" VALUES ('title_test','description_test','priority_test','10/12/2019'); ");
db.close();
// Open latest version of the database. Room will validate the schema
// once all migrations execute.
NoteDatabase appDb = Room.databaseBuilder(
InstrumentationRegistry.getInstrumentation().getTargetContext(),
NoteDatabase.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};
}
This code was working fine but , look at this reference code.这段代码工作正常,但是,看看这个参考代码。 i need to do something like this.
我需要做这样的事情。 and I'm not getting how to read
getMigratedRoomDatabase
data.我不知道如何读取
getMigratedRoomDatabase
数据。 can anyone help me on this.谁可以帮我这个事。
// MigrationTestHelper automatically verifies the schema
//changes, but not the data validity
// Validate that the data was migrated properly.
User dbUser = getMigratedRoomDatabase().userDao().getUser();
assertEquals(dbUser.getId(), USER.getId());
assertEquals(dbUser.getUserName(), USER.getUserName());
// The date was missing in version 2, so it should be null in
//version 3
assertEquals(dbUser.getDate(), null);
That is nothing but appDb
in your code.这只不过是您代码中的
appDb
。 it will look like它看起来像
appDb.userDao().getUser();
appDb.userDao().getUser();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.