I've implemented Content Provider that retrieves data from a service installed on network. The content provider takes required parameters from shared preferences (user credentials, app name, etc.)
SharedPreferences settings = getContext().getSharedPreferences(NET_PREFS, 0);
I use unit test for this Content provider:
public class ResearchProviderTest extends ProviderTestCase2<MyProvider>{
public ResearchProviderTest() {
super(MyProvider.class, MyProvider.CONTENT_AUTHORITY);
}
public void testInsert() {
ContentValues values = new ContentValues();
values.put(QueryFields.FIELD_QUERY_TEXT, "query" );
Uri newUri = getMockContentResolver().insert(MyProvider.CONTENT_URI, values);
Cursor readMessagesCursor = getMockContentResolver().query(
newUri ,
new String[] { FIELD_SR_TITLE },
null, null, null );
assertTrue("The cursor should contain some entries", readMessagesCursor.moveToFirst());
}
}
During execution of the unit test. The exception is thrown:
java.lang.UnsupportedOperationException
at android.test.mock.MockContext.getSharedPreferences(MockContext.java:127)
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
at com.company.mobile.android.net.RemoteExecutor.retrieveCredentials(RemoteExecutor.java:171)
at com.company.mobile.android.net.service.Adapter.executeSearch(Adapter.java:33)
at com.company.mobile.android.provider.MyProvider.insert(MyProvider.java:167)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:174)
...
Does anybody know how to pass Shared Preferences to the MockContext? Should I use other approach if I need Context during testing Content Provider?