Android

时间:2017-02-10 14:56:52

标签: android unit-testing robolectric

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

enter image description here

测试的目的是检查用户是否登录的布尔值的共享首选项,如果他们已登录,如果是这样,则显示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);
}

1 个答案:

答案 0 :(得分:2)

你的启动画面是否有机会?这可能是问题所在。请尝试以下方法。

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

希望这应该有用!