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> {

    @Override
    protected void setUp() throws Exception {
    super.setUp();

    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().clear();
    settings.edit().commit(); // I am pretty sure this is not necessary but not harmful either.

StartNewActivity Code:

    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setClassName(instrumentation.getTargetContext(),
            OptionScreen.class.getName());
    instrumentation.startActivitySync(intent);
    Activity currentActivity = getInstrumentation()
            .waitForMonitorWithTimeout(monitor, 5);
    assertTrue(currentActivity != null);

Thanks!

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();
editor.clear();
editor.commit();

###

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

call,

this.getInstrumentation().getTargetContext()

Leave a Reply

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