簡體   English   中英

如何通過插入和測試數據正確進行 Room 遷移測試?

[英]How to do Room migration testing properly by inserting and testing data?

我正在嘗試在包含新的 Column date后測試 Room DB。 但是我不知道如何插入數據,因為我無法在 Testing.java 文件中使用上下文。

我的代碼看起來像這樣,

@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};
}

這段代碼工作正常,但是,看看這個參考代碼。 我需要做這樣的事情。 我不知道如何讀取getMigratedRoomDatabase數據。 誰可以幫我這個事。

// 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);

這只不過是您代碼中的appDb 它看起來像

appDb.userDao().getUser();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM