Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnsupportedOperationException while calling getSharedPreferences() from unit test

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?

like image 713
Glaxalg Avatar asked Mar 11 '11 00:03

Glaxalg


1 Answers

You have to inject a Context that extends MockContext using AndroidTestCase.setContext() and overrides at least getPackageName() and getSharedPreferences().

Unfortunately, it's not possible to inject a MockContext to ProviderTestCase2 because setContext() is not honored. Then, the solution is to override setUp() not invoking the super method.

package com.example.aatg.ps.test;

import android.test.ProviderTestCase2;

import com.example.aatg.ps.ProviderSample;

public class ProviderSampleTests extends ProviderTestCase2<ProviderSample> {

    private ResolverRenamingMockContext mProviderContext;
    private Class<ProviderSample> mProviderClass;
    private ProviderSample mProvider;
    private String mProviderAuthority;

    public ProviderSampleTests() {
        super(ProviderSample.class, ProviderSample.AUTHORITY);
        setName("ProviderSampleTests");
        mProviderClass = ProviderSample.class;
        mProviderAuthority = ProviderSample.AUTHORITY;
    }

    @Override
    protected void setUp() throws Exception {
         // We should not invoke super.setUp() here to avoid the UnsupportedOperationException.
        //super.setUp();

        // This is needed to support getSharedPreferences() in ProviderSample.onCreate()
        mProviderContext = new ResolverRenamingMockContext(getContext());
        mProvider = mProviderClass.newInstance();
        assertNotNull(mProvider);
        mProvider.attachInfo(mProviderContext, null);
        mProviderContext.addProvider(mProviderAuthority, mProvider);
    }


    @Override
    public ProviderSample getProvider() {
        return mProvider;
    }

    protected void tearDown() throws Exception {
        super.tearDown();
    }

    public void testProviderSampleCreation() {
        ProviderSample provider = getProvider();
        assertNotNull(provider);
    }
}

And this is ResolverRenamingMockContext:

package com.example.aatg.ps.test;

import java.io.File;

import android.content.ContentProvider;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.test.IsolatedContext;
import android.test.mock.MockContentResolver;
import android.test.mock.MockContext;

/**
 * @author diego
 *
 */
public class ResolverRenamingMockContext extends IsolatedContext {

    /**
     * The renaming prefix.
     */
    private static final String PREFIX = "test.";


    /**
     * The resolver.
     */
    private static final MockContentResolver RESOLVER = new MockContentResolver();

    /**
     * Constructor.
     * @param context 
     */
    public ResolverRenamingMockContext(Context context) {
        super(RESOLVER, new DelegatedMockContext(context));
    }

    public MockContentResolver getResolver() {
        return RESOLVER;
    }

    public void addProvider(String name, ContentProvider provider) {
        RESOLVER.addProvider(name, provider);
    }

    /**
     * The DelegatedMockContext.
     *
     */
    private static class DelegatedMockContext extends MockContext {

        private Context mDelegatedContext;

        public DelegatedMockContext(Context context) {
            mDelegatedContext = context;
        }

        @Override
        public SharedPreferences getSharedPreferences(String name, int mode) {
            return mDelegatedContext.getSharedPreferences(PREFIX + name, mode);
        }
    }

}
like image 55
Diego Torres Milano Avatar answered Oct 03 '22 14:10

Diego Torres Milano