使用单元测试测试您的 Room 数据库

一、前言

在使用 Room 数据库时,务必需要验证数据库和用户数据的稳定性。尤其是在数据库迁移过程中,必须进行进行充分的测试,保证数据库按预定完成迁移。使用单元测试来完成这些测试,无需创建Activity, 执行速度也比界面测试速度快,可以大大提高效率。另外,在应用功能界面进行测试数据库,也并不能完全覆盖所有用例,所以使用单元测试也更加全面测试。

二、使用单元测试测试 Room 数据库

使用单元测试来测试 Room 数据库,需要编写 Android 设备上运行的 JUnit 测试单元。编写测试单元跟代码中调用数据库进行测试一样,只不过单元测测试无需创建 Activity,因此执行速度更快,通过编写完善的测试单元,完成更加全面的测试。如下示例所示:

@RunWith(AndroidJUnit4::class)
class RoomDBTest {
          
   

    lateinit var userDao: UserDao
    lateinit var studentDao: StudentDao
    lateinit var appDB: AppDatabase

    @Before
    fun createDatabase() {
          
   
        val appContext = InstrumentationRegistry.getInstrumentation().targetContext
        appDB = Room.databaseBuilder(appContext, AppDatabase::class.java, "app.db")
            .build()
        userDao = appDB.userDao()
        studentDao = appDB.studentDao()
    }

    @After
    @Throws(IOException::class)
    fun closeDB() {
          
   
        appDB?.close()
    }

    @Test
    fun insertUsers() {
          
   
        runBlocking {
          
   
            userDao.insertAll(
                User(1, "Student1", 18),
                User(2, "Student2", 18),
                User(3, "Student3", 17),
                User(4, "Student4", 19))
        }
    }

    @Test
    fun findAllUsers() {
          
   
        runBlocking {
          
   
            userDao.getAll().forEach {
          
   
                println("User { userId = ${
            
     it.userId}, name = ${
            
     it.name}, age = ${
            
     it.age}}")
            }
        }
    }

    @Test
    fun findAllStudentsWithSchool() {
          
   
        runBlocking {
          
   
            studentDao.getStudentWithSchool().forEach{
          
   
                println("Item {studentId = ${
            
     it.sid}, studentName = ${
            
     it.name}, studentAge = ${
            
     it.age}, schoolId = ${
            
     it.schoolId}, schoolName = ${
            
     it.schoolName}")
            }
        }
    }

}
注意事项:测试 Room 数据库必须编写 Android 设备上运行的 JUnit 测试单元(使用 @RunWith(AndroidJUnit4::class)标注测试类)
讲解: 上面的例子中,@Befor 是在 @Test 之前执行的,可以用来初始化数据库实例、DAO 对象等等;@After 是在 @Test 之后执行的,可用来回收资源等等;@Test 中编写测试单元代码。
经验分享 程序员 微信小程序 职场和发展