Android Unit Test : how to clear SharedPreferences

android, android-testing, sharedpreferences, unit-testing

Solution

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

Problem

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

Original source