SQLite In Android part 4: Testing the ContentProvider

If you’re reading this post I truly appreciate you sticking with me on this long adventure of understanding the ContentProvider, and I’m proud of you for wanting to go the extra mile to preform proper testing of the provider. Let’s jump right in.

Test Data

The first thing you need to define in your TestProvider class is the sample data for the rows you’ll be inserting into the database. I wrote test data for a row being inserted, as well as a value you can use to update the row:

Setup and Teardown

In order for every test case on your database to truly be handled equivalently, they should all start at the same point; For this example, they’ll start with an empty database. To do this, just implement your setup and teardown functions to delete all records:

Test getType

One of the tests you should run on your ContentProvider is a test on the getType() method, to ensure you’re getting the right MIME type. In the following code snippet I first call getType() on the provider, and ensure that the string returned matches the one I expect it to. In the GENRE tests there is a comment of the strings we expect to be returned to help you can visualize what is being tested:

Test Insert and Read

Arguably the two most common actions you will preform are writing to a database table and reading from it. In this next snippet we test our Genre Uri by writing to the genre table and then reading from it to ensure the values of the row entered match the values we attempted to insert:

The validateCursor() method is what we use to verify the values of the cursor are equal to the values inside the ContentValues we inserted. This is done by looping through the sets and comparing values based on type:

Test Update

We can test that our update method works by inserting a row, calling update, and then validating the cursor again:

After that, you’ve successfully written test cases for each of the required implementations of your ContentProvider! For simplicity I did not include the tests on the MOVIE Uri, but you can find the complete code on Github. It is important to remember that you should write a test case for every Uri used in your ContentProvider to ensure that they all work correctly.

A big thank you for all of the readers who followed along from start to finish to master the important skill of managing an SQLite database in Android. You can now have full control over your data without depending on a third party library.

Share this post...
Share on Reddit0Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Facebook0

Leave a Reply