简体   繁体   中英

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 .

在此处输入图片说明

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);
}

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM