My MainActivity on my Android application checks if the user is logged in (this is stored in SharedPreferences) and if it's not takes the user to the LoginActivity. I am trying to test this using the following code
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {
private static final int TIME_OUT = 5000; /* miliseconds */
private MainActivity mMainActivity;
private Instrumentation mInstrumentation;
private SharedPreferences mLoginPrefs;
public MainActivityTest() {
super(MainActivity.class);
}
protected void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(false);
mMainActivity = getActivity();
mInstrumentation = getInstrumentation();
mLoginPrefs = mInstrumentation.getTargetContext().getSharedPreferences(LoginActivity.PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = mLoginPrefs.edit();
// User is not logged in, so it should be redirect to LoginActivity
editor.putBoolean("logged_in", false);
editor.commit();
}
//...
public void testC_OpenLoginActivityIfUserIsNotLoggedIn() {
ActivityMonitor monitor = mInstrumentation.addMonitor(LoginActivity.class.getName(), null, false);
Activity nextActivity = mInstrumentation.waitForMonitorWithTimeout(monitor, TIME_OUT);
assertNotNull(nextActivity);
nextActivity.finish();
SharedPreferences.Editor editor = mLoginPrefs.edit();
// Login the user so we can continue the tests
editor.putBoolean("logged_in", true);
editor.commit();
}
But this doesn't work, the LoginActivity opens but waitForMonitorWithTimeout never returns so I got stuck on LoginActivity (I need to get back to MainActivity to do the other tests).
A code similar to this SO Question works for Button clicks, but this Activity is not loaded by any click so I am thinking maybe there is no time to the monitor to work.
I just need a way to get the actual Activity so I can make an assert and make it finish to continue my tests.
Just one other thing: I would prefer a method without using Robotium if it's possible.