android – 从单元测试调用getSharedPreferences()时,UnsupportedOperationException异常

前端之家收集整理的这篇文章主要介绍了android – 从单元测试调用getSharedPreferences()时,UnsupportedOperationException异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我实现了内容提供者,它从网络上安装的服务中检索数据.
内容提供者从共享首选项(用户凭据,应用程序名称等)获取所需参数
SharedPreferences settings = getContext().getSharedPreferences(NET_PREFS,0);

我为此内容提供商使用单元测试

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 );
        assertTrue("The cursor should contain some entries",readMessagesCursor.moveToFirst());
    }
}

在执行单元测试期间.抛出异常:

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)
   ...

有人知道如何将共享首选项传递给MockContext?在测试内容提供商期间是否需要Context时,应该使用其他方法吗?

解决方法

您必须注入一个使用 AndroidTestCase.setContext()扩展MockContext的上下文,并至少覆盖getPackageName()和getSharedPreferences().

不幸的是,由于setContext()不被赋值,所以不可能将MockContext注入到ProviderTestCase2中.那么解决方案是重写setUp()而不是调用super方法.

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);
    }
}

这是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);
        }
    }

}
原文链接:/android/312617.html

猜你在找的Android相关文章