Content Provider Testing Android

Rohit Singh
1 min readApr 5, 2016

--

Since Android Applications are getting more complex and smarter each day its important to have a robust database. Database operations should be tested in isolation at lower system level, at higher level through ContentProviders or at application level.

To test ContentProvider in isolation, we need mock objects that re provided by Android.

Mock objects are mimic objects used instead of calling the real domain objects to enable testing units in isolation. Android SDK provide us MockContentResolver: This is a mock implementation of the ContentResolver class that isolates the test code from the real content system. All methods are nonfunctional and throw UnsupportedOperationException if we try to use them.

Another mock object is IsolatedContext: A mock context which prevents its users from talking to the rest of the device while stubbing enough methods to satify code that tries to talk to other packages.

The ProviderTestCase2<T> class
This is a test case designed to test the ContentProvider classes.
The ProviderTestCase2 class also extends AndroidTestCase. The class template parameter T represents ContentProvider under test. Implementation of this test uses IsolatedContext and MockContentResolver.

Constructor

ProviderTestCase2(Class<T> providerClass, String providerAuthority)

Example :

public class ExampleProviderTestCase extends ProviderTestCase2<ExampleProvider> {

public ExampleProviderTestCase() {
super(ExampleProvider.class, ExampleContract.AUTHORITY);
}

public void testInsert() {
ContentValues values = new ContentValues();
values.put(ExampleContract.ExampleTable._ID, 11);
values.put(ExampleContract.ExampleTable.NAME, “Dummy”);
Uri uri = getMockContentResolver().insert(ExampleContract.ExampleTable.CONTENT_URI, values);
assertNotNull(uri);
}

public void testEmptyCursor() {
Cursor c = getMockContentResolver().query(ExampleContract.ExampleTable.CONTENT_URI, null, null, null, null);
assertNotNull(c);
c.close();
}

public void testQuery() {
Cursor c = getMockContentResolver().query(ExampleContract.ExampleTable.CONTENT_URI, null, null, null, null);
assertFalse(c.moveToFirst());
assertTrue(c.getColumnIndex(PExampleContract.ExampleTable._ID) >=0);
c.close();
}
}

--

--