Android Unit Test : how to clear SharedPreferences-ThrowExceptions

Exception or error:

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

How to solve:

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

###

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

###

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

###

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

Leave a Reply

Your email address will not be published. Required fields are marked *