Issue
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.
Solution
Found the answer here, Accessing application context from TestSuite in Setup() before calling getActivity()
Call,
this.getInstrumentation().getTargetContext()
Answered By - Jeffrey Blattman
Answer Checked By - Mildred Charles (JavaFixing Admin)