Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android unit test: clearing prefs before testing activity

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.

like image 247
Jeffrey Blattman Avatar asked Mar 01 '12 20:03

Jeffrey Blattman


1 Answers

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

Call,

this.getInstrumentation().getTargetContext()
like image 146
Jeffrey Blattman Avatar answered Oct 05 '22 22:10

Jeffrey Blattman