Android:如何在单元测试期间重置/清除应用程序首选项?

Jef*_*rod 21 android unit-testing preferences android-preferences android-activity

我想从一致的测试环境开始,所以我需要重置/清除我的偏好.这是我到目前为止测试的SetUp.它没有报告任何错误,我的测试通过了,但是没有清除偏好.

我正在测试"MainMenu"活动,但我暂时切换到OptionScreen活动(扩展了Android的PreferenceActivity类.)我确实看到测试在运行期间正确打开了OptionScreen.

 public class MyTest extends ActivityInstrumentationTestCase2<MainMenu> {
Run Code Online (Sandbox Code Playgroud)

...

    @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.
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

谢谢!

dan*_*h32 29

问题是您没有从edit()调用中保存原始编辑器,并且您获取编辑器的新实例并在其上调用commit()而未对该编辑器进行任何更改.试试这个:

Editor editor = settings.edit();
editor.clear();
editor.commit();
Run Code Online (Sandbox Code Playgroud)

  • 这也适用于settings.edit().clear().commit(); (4认同)