24

I am trying to clear all SharedPreferences added during my tests. I already read some posts and the official documentation (SharedPreferences.Editor.clear()). But when I start my application after the unit tests were run, I still found test values.

So, in the AndroidTestCase.tearDown(), I make this :

public class PrivateStorageUtilsTest extends AndroidTestCase {

private static final String KEY_SP_PACKAGE = "PrivateStorageUtilsTest";

    protected void setUp() throws Exception {
        super.setUp();

        // Clear everything in the SharedPreferences
        SharedPreferences sharedPreferences = getContext()
            .getSharedPreferences(KEY_SP_PACKAGE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();
    }

    protected void tearDown() throws Exception {
        // Clear everything in the SharedPreferences
        SharedPreferences sharedPreferences = getContext().
            getSharedPreferences(KEY_SP_PACKAGE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();
    }

}

Every other questions I found on SO was about adding commit() after the clear(), which I already done here.

EDIT 1 Adding setUp() method

EDIT 2 Providing extended class

13
  • are you using the same context to wrinte and clear the SharedPreferences?
    – Blackbelt
    Jul 22, 2013 at 15:16
  • the Context is the one provided by AndroidTestCase class. Also, when I launch my application, I still call getContext(). I can provide you the setUp() method of my unit tests if you want to.
    – mithrop
    Jul 22, 2013 at 15:22
  • yes probably it is better. Are you aware that when you run tests a different apk is update on the device test?
    – Blackbelt
    Jul 22, 2013 at 15:23
  • the setUp() method is added. And no, I was not aware of this fact. So, it really strange to still have to test values if it's not the same APK, isn't it ?
    – mithrop
    Jul 22, 2013 at 15:26
  • What class are you extending?
    – Blackbelt
    Jul 22, 2013 at 15:28

4 Answers 4

21

If you are using ActivityTestRule from Espresso, try this:

@Rule
public ActivityTestRule<MainActivity> activityTestRule =
    new ActivityTestRule<MainActivity>(MainActivity.class) {
        @Override
        protected void beforeActivityLaunched() {
            clearSharedPrefs(InstrumentationRegistry.getTargetContext());
            super.beforeActivityLaunched();
        }
    };

With a slightly modified version of stevo.mit's clearSharedPrefs:

private static final String KEY_SP_PACKAGE = "PrivateStorageUtilsTest";

/**
* Clears everything in the SharedPreferences
*/
private void clearSharedPrefs(Context context) {
    SharedPreferences prefs = 
        context.getSharedPreferences(KEY_SP_PACKAGE, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.clear();
    editor.commit();
}
1
  • One addition: Since your `clearSharedPrefs() method is independent of the test class, you should move it to helper class and make public and static so you can reuse it.
    – tir38
    Jan 29, 2016 at 21:08
13

You should extend ActivityInstrumentationTestCase2 and use getInstrumentation().getTargetContext() to get the context for the target application being instrumented (under test)

4

I run your method with AndroidJUnit4 and it works perfect when it is called as @Before and @After.

@RunWith(AndroidJUnit4.class)
@LargeTest
public class MyBusStopsTest {
    @Rule
    public ActivityTestRule<MyBusStopsActivity> mActivityRule = new ActivityTestRule<>(
            MyBusStopsActivity.class);

    @Before
    @After
    public void cleanSheredPrefs(){
        SharedPreferences sharedPreferences =
                getInstrumentation().getTargetContext().getSharedPreferences(MyBusStopsActivity.FAV_LIST, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();
    }

    @Test
    public void showChooseBusStopActivityOnFABClick() {
        onView(withId(R.id.fab)).perform(click());
        onView(withChild(withId(R.id.choose_bus_button))).check(matches(isDisplayed()));
    }
 }
1
  • For me, this only works when using @BeforeClass, instead of @Before
    – Mr-IDE
    Sep 5, 2019 at 18:44
3

You test class should extend InstrumentationTestCase.

And you should use getInstrumentation().getTargetContext().

If you need to manipulate activity directly, then your test class should extend ActivityInstrumentationTestCase2.

So your test case should look like this:

public class PrivateStorageUtilsTest extends InstrumentationTestCase {

private static final String KEY_SP_PACKAGE = "PrivateStorageUtilsTest";

    protected void setUp() throws Exception {
        super.setUp();
        clearSharedPrefs();
    }

    protected void tearDown() throws Exception {
        super.tearDown();
        clearSharedPrefs();
    }

    /**
     * Clears everything in the SharedPreferences
     */
    private void clearSharedPrefs() {
        SharedPreferences sharedPreferences = getInstrumentation().getTargetContext().
             getSharedPreferences(KEY_SP_PACKAGE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.