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

标签 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();

}

}

最佳答案

避免自动开始您的 Activity

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

完成所有设置后启动 Activity

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

关于android - 在运行测试之前设置首选项状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36893395/

相关文章:

android - 为什么 Android O 失败并显示 "does not belong to this FragmentManager!"

android - facebook native android 应用程序不接受我的 key 哈希

android - 在 Kaspresso 中比较两个 VectorDrawables 失败 - Android

android - PreferenceManager.getDefaultSharedPreferences 中的上下文有什么用?

java - Fragment中第一次调用SharedPreferences为空

android - Android 中的 Preferences 和 SharedPreferences 有什么区别?

java - AdvertisingIdClient getAdvertisingIdInfo 被主线程阻塞

android - android studio 立即删除我的复制粘贴导入语句

安卓电视测试

Android Espresso onData 奇怪的行为