Saturday, June 6, 2015

UnsupportedOperationException when testing Android ContentProvider

I was using ProviderTestCase2 to test my ContentProvider in an Android Application but always getting the UnsupportedOperationException when I tried to do any CRUD operation with my
MockContentResolver, the error message is as follow:


java.lang.UnsupportedOperationException
at android.test.mock.MockContext.openOrCreateDatabase(MockContext.java:222)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:223)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)

Eventually I figured out it's all because of this line in my onCreate method of my Provider:

dbHelper = new BillDatabaseHelper(getContext().getApplicationContext());

Because the Context I gave to the Provider is the Application Context so during a test, it's looking for the Application Context instead of the MockContext that is given by the system during testing.

After changing my onCreate method of the Provider to the following, everything works like a charm.

@Overridepublic boolean onCreate() {
   dbHelper = new BillDatabaseHelper(getContext());   return (dbHelper == null) ? false : true;}

No comments:

Post a Comment