Android Testing Handler.postDelayed

后端 未结 3 1443
自闭症患者
自闭症患者 2021-01-01 23:22

I\'m newbie on Android and get stuck on testing a SplashScreen, basically what I\'m doing is trying to test that the splash screen stays on for 3s. this is the code for the

相关标签:
3条回答
  • 2021-01-01 23:23

    In Robolectric 3.0, they updated this API. The actual version:

    ShadowLooper.runUiThreadTasksIncludingDelayedTasks();

    Usage example:

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

    Test arount it:

    @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 讨论(0)
  • 2021-01-01 23:27

    In Robolectric 3.0, IuriiO's answer would translate to-

    ShadowLooper.pauseMainLooper();
    Robolectric.getForegroundThreadScheduler().advanceBy(intervalMs);
    ShadowLooper.unPauseMainLooper();
    
    0 讨论(0)
  • 2021-01-01 23:36

    You can try:

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

    or, if you just was the runnable to be called:

    Robolectric.runUiThreadTasksIncludingDelayedTasks();
    
    0 讨论(0)
提交回复
热议问题