To begin with, we’re going to write these as Instrumented tests using the AndroidJUnit4 test class. Before we run through this class, this is what our complete class could look like:

Initialising the database

We begin in the @Before function by creating an in memory instance of our Room database. The difference with the in-memory database is that any data that has been added to the database will be cleared once the process is killed, which makes it perfect for using during tests. We simply pass in a reference to our context and the database class which is to be used for the builder.

Testing the insertBufferoos() function

This function handles the saving of our entities to the room database. So because of this, we want to go ahead and write a test to ensure that the functionality of this function remains intact.

Here we simply use the instance of the bufferoosDatabase that we created to access the DAO instance that we are testing. From here, we use the insertBufferoo() method for the DAO to insert our entity instance.

Now, we’re going to use the getBufferoos() method of the DAO to retrieve the stored bufferoos to assert that the data we inserted was saved. We do this here by checking that bufferoos.isNotEmpty().

Note: Some people will prefer to write pure SQL methods when performing operations that aren’t related to the test that you are carrying out. This does help the focus of your test methods but to keep things simpler here I haven’t done so.

Testing the getBufferoos() function

This function handles the retrieval of our entities from the room database. Because of this, we want to go ahead and write a test to ensure that the functionality of this function remains intact.

Here we again use the instance of the bufferoosDatabase and from here, we use the insertBufferoo() method for the DAO to insert our entity instances that we need in the database to test the retrieval function.

Next, we’re going to use the getBufferoos() method of the DAO to retrieve the stored bufferoos to assert that the data we inserted is returned by this function. We do this here by checking that the data we retrieve is the same as the list we originally inserted.

Testing the clearBufferoos() function

This function handles the clearing of our entities from the room database. We are going to write a test to ensure that the functionality of this function remains intact.

Here we again use the instance of the bufferoosDatabase and from here, we use the insertBufferoo() method for the DAO to insert our entity instances that we need in the database to test the retrieval function.

Next, we’re going to use the clearBufferoos() method of the DAO to clear the bufferoo entities from the database. Now want to check that this worked, so we co ahead and make use of the getBufferoos() DAO function to retrieve any stored entities from the database. We then check that the returned list is empty to ensure that the data was cleared.