22

一貫したテスト環境から始めたいので、設定をリセット/クリアする必要があります。これが私がこれまでに持っているテスト用のセットアップです。エラーは報告されておらず、テストは成功していますが、設定がクリアされていません。

「MainMenu」アクティビティをテストしていますが、一時的に OptionScreen アクティビティ (Android の PreferenceActivity クラスを拡張します) に切り替えます。実行中にテストが 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);

ありがとう!

4

2 に答える 2

30

問題は、edit() 呼び出しから元のエディターを保存していないことです。エディターの新しいインスタンスをフェッチし、そのインスタンスに変更を加えずに commit() を呼び出します。これを試して:

Editor editor = settings.edit();
editor.clear();
editor.commit();
于 2010-10-08T21:19:17.240 に答える
3

答えはここにあります、 Androidユニットテスト:アクティビティをテストする前に設定をクリアします

電話、

this.getInstrumentation().getTargetContext()
于 2012-03-01T20:43:18.150 に答える