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
// You can simply use clear() function with your variable it // will clear all the shared preferences. SharedPreferences preferences = await SharedPreferences. getInstance(); await preferences.
SharedPreferences is application specific, i.e. the data is lost on performing one of the following options: on uninstalling the application.
Removing single preference: SharedPreferences settings = context.getSharedPreferences("PreferencesName", Context.MODE_PRIVATE); settings.edit().remove("KeyName").commit();
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 should extend ActivityInstrumentationTestCase2
and use getInstrumentation().getTargetContext()
to get the context for the target application being instrumented (under test)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With