Android ApplicationTestCase using a MockContext

后端 未结 2 1016
無奈伤痛
無奈伤痛 2020-12-19 05:35

I\'m new to Android testing and I\'m trying to create an ApplicationTestCase using a MockContext (well actually I\'m trying to use a Renaming Mock Context). But I keep getti

相关标签:
2条回答
  • 2020-12-19 06:22

    As a workaround for that book sample, check the android developer guide to ApplicationTestCase: "If simply run your tests as-is, your Application will be injected with a fully-functional Context" (http://developer.android.com/reference/android/test/ApplicationTestCase.html).

    A few lines of the Setup method must be commented to get the test working:

    protected void setUp() throws Exception
        {
            super.setUp();
            // final RenamingMockContext mockContext = new RenamingMockContext(
            // getContext());
            // setContext(mockContext);
    
            createApplication();
            mApplication = getApplication();
        }
    
    0 讨论(0)
  • 2020-12-19 06:25

    I've used AndroidTestCase to mock a simple context.

    class ExampleTest extends AndroidTestCase
        public void setUp() {
          Context c = new DelegatedMockContext(getContext())
        }
    
        class DelegatedMockContext extends MockContext {
    
        private Context mDelegatedContext;
            private static final String PREFIX = "test.";
    
            public DelegatedMockContext(Context context) {
                 mDelegatedContext = context;
            }
    
            @Override
            public String getPackageName(){
                return PREFIX;
            }
    
            @Override
            public SharedPreferences getSharedPreferences(String name, int mode) {
                return mDelegatedContext.getSharedPreferences(name, mode);
            }
        }
    } 
    

    Its just a bog standard Context, but will get you going

    0 讨论(0)
提交回复
热议问题