我正在使用 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/