Android 中单元测试的奇怪行为

Strange behaviour of unit test in Android

我在 Android 中遇到一些单元测试问题。每当我 运行 我的测试他们总是失败,但是测试的预期结果和实际结果总是 相同

测试的目的是检查用户是否已登录的布尔值的共享首选项,如果他们已登录,如本例所示,则显示 DashboardActivity,如果他们未登录然后他们被带到 LoginActivity。

这是测试:

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

正在测试的逻辑:

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

您的初始屏幕是否在处理程序中?这可能是问题所在。请尝试以下操作。

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

希望能奏效!