Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 720
Jeff Axelrod Avatar asked Oct 08 '10 19:10

Jeff Axelrod


People also ask

What should I test in unit tests Android?

Unit tests or small tests only verify a very small portion of the app, such as a method or class. End-to-end tests or big tests verify larger parts of the app at the same time, such as a whole screen or user flow. Medium tests are in between and check the integration between two or more units.

What is test folder in Android Studio?

By default, Unit tests are written in src/test/java/ folder and Instrumentation tests are written in src/androidTest/java/ folder. Android studio provides Run context menu for the test classes to run the test written in the selected test classes.


2 Answers

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(); 
like image 158
danh32 Avatar answered Oct 06 '22 02:10

danh32


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

Call,

this.getInstrumentation().getTargetContext() 
like image 33
Jeffrey Blattman Avatar answered Oct 06 '22 02:10

Jeffrey Blattman