android - Android 单元测试的奇怪行为

标签 android unit-testing robolectric

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

enter image description here

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

希望这能起作用!

关于android - Android 单元测试的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42162369/

相关文章:

Android Robolectric 和矢量绘图

java - 用于向服务器发送连续值的线程

java - 我们如何 fork opencv-android repo 并在自己的项目中使用它?

python - 如何从 django_nose 覆盖范围中排除代码的特定部分

java - 如何仅在测试运行时忽略类或方法

android - 如何使用 Robolectric 测试 IntentService?

java - Android 数据绑定(bind)与选择器 View

android - 如何删除对 child parent 的看法?安卓

c# - C# 单元测试简介

unit-testing - 除了 "all of them"作为答案之外,什么类型的应用程序(具体)在单元测试中取得了真正的成功?