Android中单元测试的奇怪行为

问题描述:

我在Android中遇到了一些单元测试的问题。每当我运行我的测试他们总是失败,但预期的结果和测试的实际结果总是相同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); 
} 
+0

在调试器中查看对象id是否相同。可能不会,因为这些对象不是精确的副本 - 它们是在不同的时间创建的。 –

在由任何机会处理程序的启动画面?这可能是问题所在。尝试以下操作。

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

希望这应该工作!