Android: How do I reset/clear application preferences during unit testing?-ThrowExceptions

Exception or error:

I want to start with a consistent test environment so I need to reset/clear my preferences. Here’s the SetUp for test I have so far. It’s not reporting any errors, and my tests pass, but the preferences are not being cleared.

I’m testing the “MainMenu” activity, but I temporarily switch to the OptionScreen activity (which extends Android’s PreferenceActivity class.) I do see the test correctly open the OptionScreen during the run.

 public class MyTest extends ActivityInstrumentationTestCase2<MainMenu> {

    protected void setUp() throws Exception {

    Instrumentation instrumentation = getInstrumentation();
    Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(OptionScreen.class.getName(), null, false);

    StartNewActivity(); // See next paragraph for what this does, probably mostly irrelevant.
    activity = getActivity();
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(activity);
    settings.edit().commit(); // I am pretty sure this is not necessary but not harmful either.

StartNewActivity Code:

    Intent intent = new Intent(Intent.ACTION_MAIN);
    Activity currentActivity = getInstrumentation()
            .waitForMonitorWithTimeout(monitor, 5);
    assertTrue(currentActivity != null);


How to solve:

The problem is that you aren’t saving the original editor from the edit() call, and you fetch a new instance of the editor and call commit() on that without having made any changes to that one. Try this:

Editor editor = settings.edit();


answer is here,
android unit test: clearing prefs before testing activity



Leave a Reply

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