android unit test: clearing prefs before testing a

2019-04-30 23:55发布

问题:

I want to ensure that a preference is cleared before my Activity is started in my unit test.

The problem is that to clear the preferences, you need to call getActivity(). After that, the Activity is started, which reads the preferences.

@Override
protected void setUp() throws Exception {
    super.setUp();
    mActivity = this.getActivity();
    SharedPreferences prefs = 
       PreferenceManager.getDefaultSharedPreferences(mActivity);
    prefs.edit().clear().commit();
}

When getActivity() is called, the Activity is created, which reads the value of the pref, before the next lines clear the pref.

Is there a way obtaining a Context object without starting the Activity?

I'm new to Android unit tests, so maybe I'm missing something basic.

thanks.

回答1:

Found the answer here, Accessing application context from TestSuite in Setup() before calling getActivity()

Call,

this.getInstrumentation().getTargetContext()