Android Room数据库放置表UI测试

时间:2019-05-07 13:58:53

标签: android-room

我放下桌子,想对其进行测试。

MIGRATION_1_2确实删除了与BDao相关的'b'表。因此,AppDatabase无法获取BDao实例。另外,B :: class也从实体中删除。

@Database(entities = [A::class/*, B::class*/], version = 2)
abstract class AppDatabase : RoomDatabse() {
  abstract aDao: ADao
  // abstract bDao: BDao

  companion object {
    fun getDatabase(context: Context): AppDatabse {
      ...
      Room.databaseBuilder(context.applicationContext,
          AppDatabase::class.java, DATABASE_NAME)
          .addMigrations(MIGRATION_1_2)
          .build()
      ...
    }

    val MIGRATION_1_2 = object Migration(1, 2) {
      override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("""
            DROP TABLE 'b'
        """)
      }
    }
  }
}

下面是测试代码。我可以拿到A Dao,但是不能拿到B Dao。如何验证b表是否已删除?

@RunWith(AndroidJUnit4::class)
class MigrationTest {

  @Rule
  @JvmField
  val helper = MigrationTestHelper(
      InstrumentationRegistry.getInstrumentation(),
      AppDatabase::class.java.canonicalName,
      FrameworkSQLiteOpenHelperFactory()
   )

  @Test
  fun migrate1To2() {
    val db = helper.createDatabase(TEST_DB, 1)

    insertAData(db)
    isnertBData(db)
    db.close()

    helper.runMigrationsAndValidate(TEST_DB, 2, true, AppDatabase.MIGRATION_1_2)
    helper.closeWhenFinished(database)

    // I can test with A.
    val adao = database.aDao()

    // But I can't test with B.
    // val bdao = database.bDao()
  }
}

1 个答案:

答案 0 :(得分:0)

我写了从https://stackoverflow.com/a/7863401/2423899引用的方法

private fun AppDatabase.isTableExisting(tableName: String): Boolean {
    assert(isOpen)
    val query = SupportSQLiteQueryBuilder
            .builder("sqlite_master")
            .distinct()
            .columns(arrayOf("tbl_name"))
            .selection("tbl_name=?", arrayOf(tableName))
            .create()
    val cursor = query(query)
    val count = cursor.count > 0
    cursor.close()
    return count
}

下面的代码验证b表是否已删除。

assertThat(database.isTableExsiting("b"), `is`(false))