22

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!

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246

2 Answers2

30

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();
danh32
  • 6,234
  • 2
  • 38
  • 39
  • Thanks so much. Wow, I really should read the documentation more thoroughly. I didn't realize I was constructing an editor object; I expected that I was operating on the preferences directly. – Jeff Axelrod Oct 09 '10 at 03:47
3

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

Call,

this.getInstrumentation().getTargetContext()
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Jeffrey Blattman
  • 22,176
  • 9
  • 79
  • 134
  • Yes, that was in the code I presented. I should probably rephrase the question because it was really, "where's the bug in my code?" – Jeff Axelrod Mar 03 '12 at 14:33