Android Unit Test : how to clear SharedPreferences

mithrop picture mithrop · Jul 22, 2013 · Viewed 13.4k times · Source

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

Answer

friederbluemle picture friederbluemle · Jan 29, 2016

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();
}