Testing your database

It's important to verify the stability of your app's database and your users' data when creating databases using the Room persistence library.

There are 2 ways to test your database:

  • On an Android device.
  • On your host development machine (not recommended).

For information about testing that's specific to database migrations, see Testing Migrations.

Test on an Android device

The recommended approach for testing your database implementation is writing a JUnit test that runs on an Android device. Because these tests don't require creating an activity, they should be faster to execute than your UI tests.

When setting up your tests, you should create an in-memory version of your database to make your tests more hermetic, as shown in the following example:


class SimpleEntityReadWriteTest {
    private lateinit var userDao: UserDao
    private lateinit var db: TestDatabase

    fun createDb() {
        val context = ApplicationProvider.getApplicationContext<Context>()
        db = Room.inMemoryDatabaseBuilder(
                context, TestDatabase::class.java).build()
        userDao = db.getUserDao()

    fun closeDb() {

    fun writeUserAndReadInList() {
        val user: User = TestUtil.createUser(3).apply {
        val byName = userDao.findUsersByName("george")
        assertThat(byName.get(0), equalTo(user))


public class SimpleEntityReadWriteTest {
    private UserDao userDao;
    private TestDatabase db;

    public void createDb() {
        Context context = ApplicationProvider.getApplicationContext();
        db = Room.inMemoryDatabaseBuilder(context, TestDatabase.class).build();
        userDao = db.getUserDao();

    public void closeDb() throws IOException {

    public void writeUserAndReadInList() throws Exception {
        User user = TestUtil.createUser(3);
        List<User> byName = userDao.findUsersByName("george");
        assertThat(byName.get(0), equalTo(user));

Test on your host machine

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 your database queries.