When creating a database with Room, it is important to verify the stability of the app database and user data. There are two ways to validate your database
- A:
- Developing hosts (not recommended)
For database migration Testing, see Testing Migrations.
Note: Room allows you to mock DAO instances when running tests on your app. In this way, there is no need to create a full database object except to test the database itself. You can use this feature because your DAO does not leak any details of the database.
Test it on an Android device
It is recommended that you write Junit test databases on Android devices. Because these tests do not require Activity creation, they should be faster than UI tests.
When setting up tests, you should build an in-memory version of the database to make your database tests more closed.
@RunWith(AndroidJUnit4::class)
class SimpleEntityReadWriteTest {
private lateinit var userDao: UserDao
private lateinit var db: TestDatabase
@Before
fun createDb() {
val context = ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder(
context, TestDatabase::class.java).build()
userDao = db.getUserDao()
}
@After
@Throws(IOException::class)
fun closeDb() {
db.close()
}
@Test
@Throws(Exception::class)
fun writeUserAndReadInList() {
val user: User = TestUtil.createUser(3).apply {
setName("george")
}
userDao.insert(user)
val byName = userDao.findUsersByName("george")
assertThat(byName.get(0), equalTo(user))
}
}
Copy the code
Test on the host
Room uses the SQLite support library, which provides interfaces that match those in the Android Framework classes. This support allows you to pass custom implementations of the support library to test database queries.
Note: This setting is not recommended, although it can be used to test fast. Because the version of SQLite running on your device may not match the version running on your host
0. Overview
1. Use Room entities to define data
2. Define relationships between objects
3. Create a view in the database
4. Use Room DAOs to access data
5. Migrate the database
6. Test the database
7. Reference complex data using Room