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!
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.
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.
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()
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