Android:unit testing期间如何重置/清除应用程序首选项?

我想从一个一致的testing环境开始,所以我需要重置/清除我的首选项。 这是迄今为止我所做的testing的SetUp。 这不是报告任何错误,我的testing通过,但偏好没有被清除。

我正在testing“MainMenu”活动,但是我暂时切换到OptionScreen活动(它扩展了Android的PreferenceActivity类)。我确实看到testing在运行期间正确地打开了OptionScreen。

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代码:

  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); 

谢谢!

Solutions Collecting From Web of "Android:unit testing期间如何重置/清除应用程序首选项?"