I add this entry as I think it can help programmers that want to test their Content Provider.
Imagine your Content Provider is called MyProvider and that you have a contract class called MyProviderContract defining some constants.
First of all, you'll write a test class called MyProviderTestCase
that inherits from ProviderTestCase2<MyProvider>
. You'll have to define a constructor which will call the super
constructor:
public MyProviderTestCase() {
super(MyProvider.class, MyProviderContract.AUTHORITY);
}
Then, instead of using directly your provider (avoid using getProvider()
as users of your content provider won't access it directly), use the getMockContentResolver()
to obtain a reference to a content resolver and then call the methods of this content resolver (query
, insert
, etc.). In the following code, I show how to test the insert
method.
public void testInsert() {
Uri uri = MyProviderContract.CONTENT_URI;
ContentValues values = new ContentValues();
values.put(MyProviderContract.FIELD1, "value 1");
values.put(MyProviderContract.FIELD2, "value 2");
Uri resultingUri = getMockContentResolver().insert(uri, values);
// Then you can test the correct execution of your insert:
assertNotNull(resultingUri);
long id = ContentUris.parseId(resultingUri);
assertTrue(id > 0);
}
Then you can add as many test methods as you want, using a content resolver instead of your content provider directly, as would do users of your content provider.