Step #3: Supporting a Test Database

Right now, ToDoDatabase is set up to have a database file named stuff.db. For our “production” code, that is what we want. For tests, though, it is very convenient to have an in-memory database:

With that in mind, add this function to the companion object in ToDoDatabase:

    fun newTestInstance(context: Context) =
      Room.inMemoryDatabaseBuilder(context, ToDoDatabase::class.java).build()

This is almost identical to the newInstance() function that already exists. However, newTestInstance() uses inMemoryDatabaseBuilder() instead of databaseBuilder(), to create an in-memory SQLite database.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.