在运行测试之前设置首选项状态

时间:2016-04-27 14:50:45

标签: android android-espresso android-sharedpreferences

我正在使用espresso和AndroidJunit4跑步者。我正在尝试设置一些首选项,以便在onCreate或onResume触发时将启用该逻辑。似乎在执行onView()之前调用prefs没有任何效果。我打印出onResume和onCreate中的首选项,它们都是空的。注意shouldOpenVerifyFragement()测试用例。

关于如何做到这一点的任何想法或建议?

@RunWith(AndroidJUnit4.class)
@LargeTest
public class DriverActivityTest {
@Rule
public final ActivityTestRule<DriverActivity> sut = new ActivityTestRule<>(DriverActivity.class);

@Test
public void shouldOpenVerifyFragement() {

    Log.d("TEST", "shouldOpenVerifyFragment");
    SharedPreferences settings = sut.getActivity().getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putBoolean("status", Boolean.valueOf(false));
    editor.putString("token", "token");
    editor.commit();

    onView(withText("Pin Verify")).check(matches(isDisplayed()));
}
/**
 * Clears everything in the SharedPreferences
 */
@Before
@After
public void clearSharedPrefs() {
    SharedPreferences settings = sut.getActivity().getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.clear();
    editor.commit();

}

}

1 个答案:

答案 0 :(得分:2)

避免自动开始您的活动

sut = new ActivityTestRule<>(DriverActivity.class, false, false)

完成所有设置后启动活动

public void shouldOpenVerifyFragement() {
    ...
    editor.commit();
    sut.launchActivity(null)
    ...
}