MichaelStoddart
MichaelStoddart

Reputation: 5639

Strange behaviour of unit test in Android

I'm having an issue with some unit tests in Android. Whenever I run my test they always fail, however the expected outcome and the actual outcome of the test are always identical.

enter image description here

The aim of the test is to check shared preferences for a boolean of whether the user is logged in or not, if they are logged in, as is this case, the DashboardActivity is shown, if they aren't logged in then they are taken to the LoginActivity.

Here is the test:

@Test
public void splashActivityLaunchesDashboard(){
    SharedPreferences sharedPreferences = RuntimeEnvironment.application.getSharedPreferences("UNISAAS", Context.MODE_PRIVATE);
    sharedPreferences.edit().putBoolean(Constants.PREF_USER_LOGGED_IN, true).commit();

    Class clazz = DashbordActivity.class;
    Intent expectedIntent2 = new Intent(activity, clazz);

    presenter.checkUserLoggedIn(sharedPreferences);
    ShadowActivity shadowActivity = Shadows.shadowOf(activity);
    Intent actualIntent2 = shadowActivity.getNextStartedActivity();
    assertEquals(expectedIntent2, actualIntent2);
}

And the logic being tested:

@Override
public void checkUserLoggedIn(SharedPreferences preferences) {

    if (preferences.getBoolean(Constants.PREF_USER_LOGGED_IN, false)) {
        mSplashView.switchToDashboard();
    } else {
        mSplashView.switchToLogin();
    }
}

@Override
public void switchToLogin() {
    Intent loginIntent = new Intent(this, LoginActivity.class);
    startActivity(loginIntent);
}

@Override
public void switchToDashboard() {
    Intent dashboardIntent = new Intent(this, DashbordActivity.class);
    startActivity(dashboardIntent);
}

Upvotes: 2

Views: 70

Answers (1)

drofnnuD
drofnnuD

Reputation: 76

Is your splash screen in a handler by any chance? This could be where the issue is. Try the following.

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            presenter.checkUserLoggedIn(sharedPreferences);
            ShadowActivity shadowActivity = Shadows.shadowOf(activity);
            Intent actualIntent2 = shadowActivity.getNextStartedActivity();
            assertEquals(expectedIntent2, actualIntent2);
        }
    }, timeHere);

Hopefully that should work!

Upvotes: 2

Related Questions