2014-07-08 47 views
5

我是Android新手,在測試SplashScreen時遇到困難,基本上我正在試圖測試啓動屏幕保持3秒。這是濺射屏幕Android測試Handler.postDelayed

@Override 
protected void onStart() { 
    super.onStart(); 

    new Handler().postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      Intent i = new Intent(SplashScreenActivity.this, MainActivity.class); 
      startActivity(i); 
      finish(); 
     } 
    }, SPLASH_TIME_OUT); 
} 

的代碼,這是我的測試方法:

@Test 
public void splashScreenTimerTest() throws InterruptedException { 
    StopWatch timer = new StopWatch(); 
    timer.start(); 

    splashScreenActivityController.start(); 

    timer.stop(); 
    long expected = 3000L; 
    assertThat(String.format("The spalash screen run for longer than expected. It should stay on for [%d] but it run for [%d]",expected,timer.getTime()),timer.getTime(),equalTo(expected)); 
} 

我使用的Android + Robolectric進行測試。

我一直在谷歌搜索了幾天,我嘗試了很多東西,但沒有結果。我嘗試獲取UI線程並等待它。我試圖讓你的調度程序來獲取隊列,看看那裏是否有任何任務。但根本沒有結果。

任何建議如何讓我的測試等到新的活動被觸發?

感謝

回答

7

你可以試試:

Robolectric.pauseMainLooper(); 
Robolectric.getUiThreadScheduler().advanceBy(intervalMs); 
Robolectric.unPauseMainLooper(); 

,或者,如果你只是將叫可運行:

Robolectric.runUiThreadTasksIncludingDelayedTasks(); 
+0

感謝他LP,我會再檢查! – Rabel

+0

像魅力的偉大作品 –

13

Robolectric 3.0,他們更新了這個API。實際的版本:

ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

用例:

public class MainActivity extends AppCompatActivity { 
    ........ 

    public void finishGame() { 
     Handler h = new Handler(); 
     h.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       finish(); 
      } 
     }, 5000); 
    } 
} 

測試arount它:

@RunWith(RobolectricTestRunner.class) 
@Config(constants = BuildConfig.class, sdk=21) 
public class MainActivityTest { 

    @Test 
    public void testFinishing() throws InterruptedException { 
     MainActivity mainActivity = new MainActivity(); 

     assertFalse(mainActivity.isFinishing()); 

     mainActivity.finishGame(); 
     ShadowLooper.runUiThreadTasksIncludingDelayedTasks(); 

     assertTrue(mainActivity.isFinishing()); 
    } 
} 
+0

哦!謝謝 :) – cVoronin

2

在Robolectric 3.0,IuriiO的回答會轉化TO-

ShadowLooper.pauseMainLooper(); 
Robolectric.getForegroundThreadScheduler().advanceBy(intervalMs); 
ShadowLooper.unPauseMainLooper();