Testing Your ContentProvider with Robolectric

You like testing?  I love testing, especially unit testing.  ContentProviders are the underpinnings of many data layer implementations in Android apps and obviously, an important thing to test.  I added some new code to a ContentProvider in the RadioPublic app and wanted to verify that the ContentProvider and model code worked.  I spent an hour looking through the documentation and online. I also wanted to use the Robolectric test framework already setup in the app.  After concluding my research, I found what I was looking for and its very straightforward.

First of all, if you haven’t already done so, in your module’s build.gradle file, depedencies section:

testCompile 'junit:junit:4.12'
testCompile 'org.robolectric:robolectric:3.1.1'

In your unit test class, class annotations

@Config(constants = BuildConfig.class, sdk = 18)

Register your ContentProvider with the appropriate Authority:

private static final String AUTHORITY = "com.example.debug";

public void setup() {
    YourProvider provider = new YourProvider();
            AUTHORITY, provider

Get a reference to the ContentResolver, since this is, most likely, how you’ll be interacting with your provider:

ContentResolver contentResolver = RuntimeEnvironment.application.getContentResolver();

Finally, test your ContentProvider

public void getSomeData() {
   cursor = contentResolver.query(Test.MyUri, null, null, null, null);

That’s it!  Hopefully this will save you time and encourage you to write tests for your ContentProviders.